Python 如何指定 Tkinter 窗口打开的位置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14910858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to specify where a Tkinter window opens?
提问by xxmbabanexx
How can I tell a Tkinter window where to open, based on screen dimensions? I would like it to open in the middle.
如何根据屏幕尺寸告诉 Tkinter 窗口在哪里打开?我希望它在中间打开。
采纳答案by xxmbabanexx
This answer is based on Rachel's answer. Her code did not work originally, but with some tweaking I was able to fix the mistakes.
这个答案是基于瑞秋的答案。她的代码最初不起作用,但通过一些调整我能够修复错误。
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
回答by Rachel Gallen
Try this
尝试这个
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()
回答by LordDraagon
root.geometry('250x150+0+0')
The first two parameters are the width and height of the window. The last two parameters are x and y screen coordinates. You can specify the required x and y coordinates
前两个参数是窗口的宽度和高度。最后两个参数是 x 和 y 屏幕坐标。您可以指定所需的 x 和 y 坐标
回答by bala subramani
root.geometry('520x400+350+200')
root.geometry('520x400+350+200')
Explanation: ('width x height + X coordinate + Y coordinate')
说明:('宽x高+X坐标+Y坐标')

