我们可以阻止按钮和小部件互相干扰吗?

时间:2017-11-26 08:47:17

标签: tkinter python-3.6

在tkinter中,我发现自己放置了小部件,即使它们位于不同的行上,它们也相互干扰,例如:

from tkinter import *
from tkinter import ttk
root = Tk()
multi = Button(root , text ='multiplication')
multi.grid(row = 0 , column = 1 , sticky = W)


addition = Button(root , text = 'addition')
addition.grid(row = 0 , column = 0 , sticky = W)

question = Label(root ,text = 'What is 500 + 500?', font = 'times 10 bold')
question.grid(row = 1, column = 0 , sticky =W)
root.mainloop()

有没有办法解决这个问题,我可以把它放在彼此不干扰的地方,即使它们是在单独的行上吗?我的标签在上面的行中完全搞砸了我的按钮

1 个答案:

答案 0 :(得分:0)

如果列中有两个小部件,则tkinter会将列调整为更大的小部件。

您可以使用sticky="we"将按钮大小调整为列大小。

from tkinter import *
from tkinter import ttk

root = Tk()

multi = Button(root, text='multiplication')
multi.grid(row=0, column=1, sticky="we") # <---

addition = Button(root, text='addition')
addition.grid(row=0, column=0, sticky="we")

question = Label(root, text='What is 500 + 500?', font='times 10 bold')
question.grid(row=1, column=0, sticky="we")

root.mainloop()

或者使用可以columnspan=2 Label将其放在两列

from tkinter import *
from tkinter import ttk

root = Tk()

multi = Button(root, text='multiplication')
multi.grid(row=0, column=1, sticky="w")

addition = Button(root, text='addition')
addition.grid(row=0, column=0, sticky="w")

question = Label(root, text='What is 500 + 500?', font='times 10 bold')
question.grid(row=1, column=0, sticky="w", columnspan=2) # <---

root.mainloop()

参见effbot.org:The Tkinter Grid Geometry Manager