66

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

4

5 回答 5

100

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

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
于 2013-02-16T16:47:26.627 回答
43

试试这个

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()

来源

于 2013-02-16T13:35:25.667 回答
27
root.geometry('250x150+0+0')

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

于 2017-05-26T08:49:30.897 回答
5

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

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设备屏幕。

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

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

于 2020-07-13T06:11:45.687 回答
1

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

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

于 2019-03-22T04:59:38.307 回答