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

xxm*_*exx 47 python tkinter python-2.7

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

xxm*_*exx 72

这个答案是基于雷切尔的答案.她的代码最初没有用,但经过一些调整我能够解决错误.

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
Run Code Online (Sandbox Code Playgroud)


Rac*_*len 33

试试这个

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()
Run Code Online (Sandbox Code Playgroud)

资源

  • @RachelGallen:您是否意识到代码是针对完全不同的工具包的?您不能使用pyqt来居中tkinter窗口. (2认同)

Lor*_*gon 17

root.geometry('250x150+0+0')
Run Code Online (Sandbox Code Playgroud)

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


Mat*_*mer 7

如果您希望窗口居中,此类功能可能会帮助您:

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
Run Code Online (Sandbox Code Playgroud)

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

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

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


小智 6

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

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

  • 你的答案和@LordDraagon的答案有什么区别? (5认同)