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

时间:2013-02-16 13:30:50

标签: python python-2.7 tkinter

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

5 个答案:

答案 0 :(得分:65)

此答案基于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

答案 1 :(得分:31)

试试这个

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

答案 2 :(得分:12)

root.geometry('250x150+0+0')

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

答案 3 :(得分:0)

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

说明:(“宽度x高度+ X坐标+ Y坐标”)

答案 4 :(得分:0)

如果您希望窗口居中。

那么这种类型的功能可能会帮助您-:

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函数用于获取设备屏幕的宽度。 window.winfo_screenheight函数用于获取设备屏幕的高度。

这些可以在python的Tk窗口中调用。

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

您可以根据需要自定义计算方式,该计算方式将相应更改。