使用Tkinter的Python GUI - 小部件位置不正确
我正在创建一个图形用户界面(GUI),里面有一个 TextBox
和几个 Button
。
现在遇到的问题是,布局看起来很乱。当我增加行数以便更好地分隔时,似乎没有任何变化。我不太确定自己哪里出错了。
代码如下:
from Tkinter import *
from tkFileDialog import *
gui = Tk() #create an object
gui.title("xyz")
gui.geometry("900x300")
GuiLabel1 = Label(gui,text="hi everyone!!!!!!")
GuiLabel1.grid(row=0, column=0)
GuiLabel2 = Label(gui,text="File")
GuiLabel2.grid(row=1, column=0)
bar=Entry(gui)
bar.grid(row=1, column=1)
button1= Button(gui, text="Browse")
button1.grid(row=1, column=2)
button2= Button(gui, text="Process")
button2.grid(row=2, column=2)
button3= Button(gui, text="ABC")
button3.grid(row=3, column=0)
button4= Button(gui, text="ABC")
button4.grid(row=3, column=1)
button5= Button(gui, text="ABC")
button5.grid(row=3, column=2)
button6= Button(gui, text="ABC")
button6.grid(row=3, column=3)
button7= Button(gui, text="ABC")
button7.grid(row=3, column=4)
gui.mainloop()
下面是这个图形用户界面的截图:
3 个回答
-3
我觉得你可能在寻找一种组合方式,
pack()
grid()
还有一个叫做 Frame
的元素,它可以让你把多个元素“组合”在一起,这样它们就算作一个元素了。
我不能直接帮你修复代码,但我建议你去了解这些内容,试试看。
1
这些小部件的显示方式基本上是你所设置的那样。问题在于,你依赖了很多默认的定位方式,这可能就是它们没有按照你想的样子出现在屏幕上的原因。
当你使用网格布局时,几乎总是应该加上 sticky
选项,这样可以定义小部件如何填充它所在的单元格。你通常还需要加上内边距。最后,通常至少要给一行和一列设置一个非零的权重。
另外,记住你是在创建一个网格。如果网格中有一个非常宽的项目,那么整个列都会变得很宽。如果你在后面的行中放置较小的项目,它们默认会在那一列中居中显示。
0
你可以使用“width=”这个参数来让小部件(比如按钮)均匀分布,具体可以参考这个链接:http://effbot.org/tkinterbook/button.htm。另外,你还可以用row/columnconfigure来显示空的行或列。
from Tkinter import *
gui = Tk() #create an object
gui.title("xyz")
gui.geometry("900x300")
GuiLabel1 = Label(gui,text="hi everyone!!!!!!")
GuiLabel1.grid(row=0, column=0)
GuiLabel2 = Label(gui,text="File")
GuiLabel2.grid(row=3, column=0)
bar=Entry(gui)
bar.grid(row=1, column=1)
button1= Button(gui, text="Browse", width=test_width)
button1.grid(row=1, column=2)
button2= Button(gui, text="Process", width=test_width)
button2.grid(row=2, column=2)
test_width=20
for ctr in range(4):
button= Button(gui, text="ABC"+str(ctr+1), width=test_width)
button.grid(row=3, column=ctr)
## empty column between
gui.columnconfigure(4, minsize=50)
button7= Button(gui, text="ABC")
button7.grid(row=3, column=5)
gui.mainloop()