如何仅在主显示器上居中显示窗口



我有多个显示器,当我试图将窗口放在屏幕中央时,它会移到屏幕的左边缘。代码:

def center_window(window, window_width, window_height, offset_x=0, offset_y=0):
s_width = window.winfo_screenwidth()
s_height = window.winfo_screenheight()
x_cordinate = int((s_width/2) - (window_width/2))
y_cordinate = int((s_height/2) - (window_height/2))
window.geometry("{}x{}+{}+{}".format(window_width, window_height, x_cordinate+offset_x, y_cordinate+offset_y))

如果我禁用监视器,就不会发生这种情况,并且窗口会正确居中。

我尝试了其他的解决方案,正如在这个问题中所解释的:如何在Tkinter中将窗口居中?

没有一个答案在多监视器设置下工作。顺便说一下,我在Ubuntu22-04上。谢谢你的帮助,我会很感激的。

左上角(0,0)的Monitor通常是主屏幕。考虑到这一点,您可以简单地使用geometry('+0+0')定位窗口,调用update_idletasks(),然后向winfo_screenwidth()询问窗口的屏幕宽度和高度,并进行通常的计算。

专业提示:当你不想看到一个窗口翻转在你的屏幕上设置,你可以使用wm_attributes('-alpha')使你的动作不可见。

def center_window(window, window_width, window_height, offset_x=0, offset_y=0):
window.wm_attributes('-alpha',0)#hide window
window.geometry("{}x{}+{}+{}".format(window_width, window_height, 0,0) #0,0 primary Screen
window.update_idletasks() #make sure the properties are updated
s_width = window.winfo_screenwidth()
s_height = window.winfo_screenheight()
x_cordinate = int((s_width/2) - (window_width/2))
y_cordinate = int((s_height/2) - (window_height/2))
window.geometry("{}x{}+{}+{}".format(window_width, window_height, x_cordinate+offset_x, y_cordinate+offset_y))
window.wm_attributes('-alpha',1)#show window

最新更新