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