2013-02-16 53 views

回答

46

這個答案是基於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 
21

試試這個

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

+0

或參考http://eurion.net/python-snippets/snippet/Center %20window.html替代方法 – 2013-02-16 13:38:44

+1

最大的用處,你可能想要修復你的縮進。 – mgilson 2013-02-16 13:56:19

+1

@RachelGallen:你是否意識到代碼是一個完全不同的工具包?你不能使用pyqt來定位一個tkinter窗口。 – 2013-02-16 16:31:08

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

使用這前兩個參數是該窗口的寬度和高度。最後兩個參數是x和y屏幕座標。您可以指定所需的x和y座標