Python 2.7 - 使用.pack()在Tkinter框架中居中控件

时间:2016-04-01 23:43:51

标签: python python-2.7 tkinter pack

我尝试使用.pack()方法将所有标签和输入框移到屏幕中间。我尝试使用

anchor = CENTER

使用.place()方法,但这使得一切都在中心重叠。如何简单地将我的所有小部件移动到我的Tkinter框架的中心?

这是我的代码:

from Tkinter import *

root = Tk()
root.minsize(width = 500, height = 500)
root.wm_title("Email Program v1.0")

def callback():
    print ("Hello!")

#sign in - email
usernameLabel = Label(root, text = "Email:")
usernameLabel.pack(padx = 0, pady = 0)

usernameInput = Entry(root)
usernameInput.pack()
usernameInput.focus_set()

passwordLabel = Label(root, text = "Password:")
passwordLabel.pack()

passwordInput = Entry(root, show = "*", width = 20)
passwordInput.pack()
passwordInput.focus_set()

#submit email credentials - connect to the server
submitEmail = Button(root, text = "Submit", fg = "black", width = 10, command = callback)
submitEmail.pack()

root.mainloop()

2 个答案:

答案 0 :(得分:2)

我设法使用三个框架将这些标签和条目放到中心,两个框架没有任何内容只是为了“占用”空间。

frame1 = Frame(root)
frame1.pack(expand=True)

frame2 = Frame(root)

usernameLabel = Label(frame2, text = "Email:")
usernameLabel.pack(padx = 0, pady = 0)

usernameInput = Entry(frame2)
usernameInput.pack()
usernameInput.focus_set()

passwordLabel = Label(frame2, text = "Password:")
passwordLabel.pack()

passwordInput = Entry(frame2, show = "*", width = 20)
passwordInput.pack()
passwordInput.focus_set()
submitEmail = Button(frame2, text = "Submit", fg = "black", width = 10, command\
 = callback)
submitEmail.pack()

frame2.pack(anchor=CENTER)

frame3 = Frame(root)
frame3.pack(expand=True)

答案 1 :(得分:0)

简单的解决方案是将所有小部件放在一个框架中,然后将框架居中。