我一直在学习一些基本的tkinter,并且遇到了一些简单的代码来将窗口居中放置在监视器的中间,除了运行时它是水平关闭的。这很花哨,但让我很困扰。我使用的代码
# Imports
from tkinter import *
# tkinter Application
root = Tk()
#Root Geometry
root_Width = 600
root_Length = 600
# Coordinates of top left pixel of application for centred
x_left = int(root.winfo_screenwidth()/2-root_Width/2)
y_top = int(root.winfo_screenheight()/2-root_Length/2)
root_Pos = "+" + str(x_left) + "+" + str(y_top)
# Window size and position
root.geometry(str(root_Width) + "x" + str(root_Length) + root_Pos)
root.mainloop()
即使我基本操作,只是尝试打开显示器大小(1920x1080)为0,0的窗口,它也会在水平方向上错位8px。
from tkinter import *
root = Tk()
root.geometry("1920x1080+0+0")
root.mainloop()
我截取了以下结果的屏幕截图:
我设置了双监视器,因此我在正确的监视器开始处添加了一条红线。我不知道问题是什么或如何解决。如果我改成
root.geometry("1920x1080+-8+0")
It opens where it should, but I want to fix this in general preferably. I want 0,0 to be the top left pixel of the monitor. I acknowledge the issue may not be with python, but any advice would be helpful.
Ok, there are two thing that you are missing. The first, in your first example, is that you need to assure tkinter is getting the right values, and to do this you have to use update_idletasks()
method before any winfo
.
第二件事解释了为什么您必须使用-8
全屏窗口居中,这是tkinter寡妇具有外部框架。您可以通过检查窗口(winfo_rootx()
)和外部框架(winfo_x()
)的左上角坐标来确定该框架的大小。现在,框架宽度是两者之间的差异:frame_width = root.winfo_rootx() - root.winfo_x()
而实际窗口宽度是real_width = root.winfo_width() + (2*frame_width)
,因为您必须考虑两侧的框架。
总之,要使窗口水平居中,请执行以下操作:
width = root.winfo_width()
frame_width = root.winfo_rootx() - root.winfo_x()
real_width = root.winfo_width() + (2*frame_width)
x = root.winfo_screenwidth() // 2 - real_width // 2
(在这里您可以打印框架宽度,您将看到它是8
)
然后使用geometry
方法将窗口放置在位置x
。
当然,您可以对垂直对齐进行相同的操作
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句