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

2024-04-26 05:55:41 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

这个答案是基于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

试试这个

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

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

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

相关问题 更多 >