如何指定 Tkinter 窗口的打开位置?

Posted

技术标签:

【中文标题】如何指定 Tkinter 窗口的打开位置?【英文标题】:How to specify where a Tkinter window opens? 【发布时间】:2013-02-01 09:09:44 【问题描述】:

如何根据屏幕尺寸告诉 Tkinter 窗口在哪里打开?我希望它在中间打开。

【问题讨论】:

an answer 【参考方案1】:

如果您希望窗口居中,这种类型的功能可能会帮助您:

def center_window(size, window) :
    window_width = size[0] #Fetches the width you gave as arg. Alternatively window.winfo_width can be used if width is not to be fixed by you.
    window_height = size[1] #Fetches the height you gave as arg. Alternatively window.winfo_height can be used if height is not to be fixed by you.
    window_x = int((window.winfo_screenwidth() / 2) - (window_width / 2)) #Calculates the x for the window to be in the centre
    window_y = int((window.winfo_screenheight() / 2) - (window_height / 2)) #Calculates the y for the window to be in the centre

    window_geometry = str(window_width) + 'x' + str(window_height) + '+' + str(window_x) + '+' + str(window_y) #Creates a geometric string argument
    window.geometry(window_geometry) #Sets the geometry accordingly.
    return

这里window.winfo_screenwidth函数用于获取设备屏幕的width。 而window.winfo_screenheight函数用于获取设备屏幕的height

在这里你可以调用这个函数,并传递一个以屏幕的(宽度,高度)为大小的元组。

您可以根据需要自定义计算,它会相应更改。

【讨论】:

与上述答案的简单区别,但适用于不同的单个窗口,这很好【参考方案2】:

root.geometry('520x400+350+200')

解释:('宽x高+X坐标+Y坐标')

【讨论】:

你的回答和@LordDraagon 的回答有什么区别?【参考方案3】:
root.geometry('250x150+0+0')

前两个参数是窗口的宽度和高度。最后两个参数是 x 和 y 屏幕坐标。您可以指定所需的 x 和 y 坐标

【讨论】:

很好的通用解决方案,让用户更加灵活。谢谢!【参考方案4】:

试试这个

import tkinter as tk


def center_window(width=300, height=200):
    # get screen width and height
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()

    # calculate position x and y coordinates
    x = (screen_width/2) - (width/2)
    y = (screen_height/2) - (height/2)
    root.geometry('%dx%d+%d+%d' % (width, height, x, y))


root = tk.Tk()
center_window(500, 400)
root.mainloop()

Source

【讨论】:

或参考eurion.net/python-snippets/snippet/Center%20window.html了解替代方法 为了获得最大的实用性,您可能需要修复缩进。 @RachelGallen:您是否意识到代码用于完全不同的工具包?您不能使用 pyqt 将 tkinter 窗口居中。 @BryanOakley 我提供了另一种解决方案。除了他说他在 python 中工作,为什么不呢? 在 windows 7 上使用 python 2.6 对我来说效果很好【参考方案5】:

此答案基于Rachel's answer。她的代码最初无法正常工作,但经过一些调整,我能够修复错误。

import tkinter as tk


root = tk.Tk() # create a Tk root window

w = 800 # width for the Tk root
h = 650 # height for the Tk root

# get screen width and height
ws = root.winfo_screenwidth() # width of the screen
hs = root.winfo_screenheight() # height of the screen

# calculate x and y coordinates for the Tk root window
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)

# set the dimensions of the screen 
# and where it is placed
root.geometry('%dx%d+%d+%d' % (w, h, x, y))

root.mainloop() # starts the mainloop

【讨论】:

以上是关于如何指定 Tkinter 窗口的打开位置?的主要内容,如果未能解决你的问题,请参考以下文章

Python图形用户界面

如何让tkinter自动关闭窗口后显示另一个窗口?

如何同时打开 Pygame 窗口和 Tkinter 窗口?

在 MS-Windows 下调整大小导致的 Tkinter 性能问题

如何使用 python 3 tkinter/guizero 在主窗口中间启动第二个窗口?

如何在 tkinter 窗口中打开 cv2 窗口