如何在Tkinter中将窗口居中显示?
在Tkinter GUI编程中,居中显示窗口是一个非常常见的需求。本篇文章将介绍如何使用Python和Tkinter在屏幕中央显示窗口,让你的应用程序更加专业化。
计算屏幕中央的位置
要将Tkinter窗口居中显示,需要先计算屏幕中央的位置。可以使用Python的Tkinter库中的方法winfo_screenwidth()
和winfo_screenheight()
获取屏幕的高度和宽度,然后使用以下公式计算窗口的屏幕中央位置:
x = int((root.winfo_screenwidth() - root.winfo_reqwidth()) / 2)
y = int((root.winfo_screenheight() - root.winfo_reqheight()) / 2)
winfo_reqwidth()
和winfo_reqheight()
方法将返回窗口需要的宽度和高度,如果在窗口创建之前使用,它们会返回0。
以下是一个简单的示例,演示如何计算屏幕中央的位置:
from tkinter import *
#创建主窗口
root = Tk()
#确定窗口大小
root.geometry("400x300")
#计算屏幕中央的位置
x = int((root.winfo_screenwidth() - root.winfo_reqwidth()) / 2)
y = int((root.winfo_screenheight() - root.winfo_reqheight()) / 2)
#将窗口居中显示
root.geometry("+{}+{}".format(x, y))
#启动主循环
root.mainloop()
运行以上程序,可以看到Tkinter窗口被完美地居中显示在屏幕上。
将计算位置封装为函数
为方便调用,将计算屏幕中央位置的代码封装到一个函数中。以下是一个示例代码:
from tkinter import *
def center_window(root, width, height):
#获取屏幕尺寸
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
#计算窗口居中显示的参数
size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
#设置窗口居中显示
root.geometry(size)
#创建主窗口
root = Tk()
root.title('居中测试')
#设置窗口大小
width = 400
height = 300
center_window(root, width, height)
#启动主循环
root.mainloop()
运行以上程序,窗口将自动居中显示,无需手动输入位置参数。
综合示例
最后,我们将以上两个示例结合起来,创建一个完整的示例程序,演示如何创建居中窗口:
from tkinter import *
def center_window(root, width, height):
#获取屏幕尺寸
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
#计算窗口居中显示的参数
size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
#设置窗口居中显示
root.geometry(size)
def main():
#创建主窗口
root = Tk()
root.title("居中窗口测试")
#设置窗口大小并居中显示
width = 500
height = 300
center_window(root, width, height)
#设置标签
label = Label(root, text="居中显示窗口", font=("Arial", 16))
label.pack()
#启动主循环
root.mainloop()
if __name__ == '__main__':
main()
运行以上程序,Tkinter窗口将完美地居中显示,标签“居中显示窗口”也居中显示在窗口内。
结论
以上就是使用Python和Tkinter实现居中显示窗口的方法,通过计算屏幕中央位置并使用geometry()
方法将窗口设置为居中显示。无论是简单的窗口还是复杂的GUI应用程序,这些示例代码都能轻松实现窗口的居中显示。