python Tkinter程序显示在屏幕中央

Python评论414阅读模式

要让Tkinter程序显示在屏幕中央,可以使用以下代码:

import tkinter as tk

class MyApplication:
    def __init__(self, master):
        self.master = master
        self.master.title("My Application")
        self.master.geometry("300x200")
        self.center_window()

    def center_window(self):
        screen_width = self.master.winfo_screenwidth()
        screen_height = self.master.winfo_screenheight()
        x = int((screen_width - self.master.winfo_reqwidth()) / 2)
        y = int((screen_height - self.master.winfo_reqheight()) / 2)
        self.master.geometry("+{}+{}".format(x, y))

if __name__ == "__main__":
    root = tk.Tk()
    app = MyApplication(root)
    root.mainloop()

在这个例子中,我们定义了一个名为`center_window`的方法,该方法将窗口居中显示。我们使用`winfo_screenwidth`和`winfo_screenheight`方法获取屏幕的宽度和高度,然后计算出窗口的x和y坐标,以便将其居中。最后,我们使用`geometry`方法将窗口移动到指定的位置。文章源自爱尚资源教程网-https://www.23jcw.net/6565.html 文章源自爱尚资源教程网-https://www.23jcw.net/6565.html

相关文章
版权声明:文章图片资源来源于网络,如有侵权,请留言删除!!!
  • 温馨提示:如遇到资源下载不了,或者文章没有解决你的问题的,可以联系我们帮你处理!!!
  • 转载请务必保留本文链接:https://www.23jcw.net/6565.html

发表评论