1 # 窗口居中顯示 2 import tkinter as tk 3 4 5 def set_win_center(root, curWidth='', curHight=''): 6 ''' 7 設置窗口大小,並居中顯示 8 :param root:主窗體實例 9 :param curWidth:窗口寬度,非必填,默認200 10 :param curHight:窗口高度,非必填,默認200 11 :return:無 12 ''' 13 if not curWidth: 14 '''獲取窗口寬度,默認200''' 15 curWidth = root.winfo_width() 16 if not curHight: 17 '''獲取窗口高度,默認200''' 18 curHight = root.winfo_height() 19 # print(curWidth, curHight) 20 21 # 獲取屏幕寬度和高度 22 scn_w, scn_h = root.maxsize() 23 # print(scn_w, scn_h) 24 25 # 計算中心坐標 26 cen_x = (scn_w - curWidth) / 2 27 cen_y = (scn_h - curHight) / 2 28 # print(cen_x, cen_y) 29 30 # 設置窗口初始大小和位置 31 size_xy = '%dx%d+%d+%d' % (curWidth, curHight, cen_x, cen_y) 32 root.geometry(size_xy) 33 34 35 root = tk.Tk() 36 root.resizable(False, False) # 窗口不可調整大小 37 root.title('窗口居中顯示') 38 root.update() # 必須 39 set_win_center(root, 300, 300) 40 root.mainloop()
運行結果:
200 200 1924 1062 862.0 431.0