Python Tkinter按钮相距甚远

时间:2015-10-09 13:03:37

标签: python user-interface tkinter

我一直在学习一些python,我已经开始开发一个应用程序,它允许用户使用Tkinter按钮和字段在Tkinter窗口中使用GUI和Canvas制作一些艺术作品。 buttons are very far apart

然而,由于某种原因,所有这些按钮相距甚远,我不确定它们的确切位置是什么逻辑。这是我的代码,它设置窗口和按钮:

area = Canvas(self)
area.grid(row = 1, column=0, columnspan=2, rowspan=28, padx=5, sticky = E+W+S+N)
#columns
self.columnconfigure(1, weight=1)
self.columnconfigure(3, pad=7)
self.rowconfigure(3, weight=1)
self.rowconfigure(5, pad=7)
#Background Colour 
colourL = Label(self, text="Background colour:")
colourL.grid(row=1, column=3)
colourbg = Entry(self)
colourbg.grid(row = 1, column=4)
#Turtle Colour
turtcL = Label(self, text="Turtle colour:")
turtcL.grid(row=2, column=3)
turtcol = Entry(self)
turtcol.grid(row = 2, column=4)
setCol=Button(self, text="Set colours",command=lambda: setColour(alex,turtcol.get(),area,colourbg.get()) )
setCol.grid(row=2, column=5)
#Fractal Button
fractalL = Label(self, text="Order of Fractal:")
fractalL.grid(row=5, column=4)
fractorder = Entry(self)
fractorder.grid(row = 6, column=4)
#Buttons
drawButton = Button(self, text="Draw", command=lambda: draw(100, turtles, 80))
drawButton.grid(row=3, column=3)

如果有人可以告诉我为什么以及如何让按钮和字段更加紧密,我将非常感激。

1 个答案:

答案 0 :(得分:2)

在您的问题中没有足够的代码来说明发生了什么。我的猜测是第3排的重量比其他排的重量大。

但是,我建议对如何创建GUI进行两处修改,而不是追逐错误。

首先,不要试图将所有内容都放在一个网格中,而是将GUI分成两半。一半有画布,没有别的,另一半有一堆按钮。对我来说,自然组织首先要创建一个包含按钮的框架。然后,使用pack将画布放在左侧,将框架放在右侧。

一旦你有了这个工作,你可以组织你的按钮,而不必担心按钮网格和画布之间的交互。

其次,将您对grid的所有电话放在一起,这样您就可以更轻松地同时查看所有内容。

它看起来像下面这样。请注意,所有按钮都使用control作为其父级。此外,条目小部件使用sticky选项填充他们已经给出的空间。如果您希望它们都是统一尺寸,您也可以使用按钮。您还可以使用sticky属性将标签向左或向右排列,具体取决于您希望GUI的外观。

...
# create the two sides:
area = Canvas(self)
controls = Frame(self)

area.pack(side="left", fill="both", expand=True)
controls.pack(side="right", fill="both", expand=False)

# create the buttons and labels
colourL = Label(controls, text="Background colour:")
colorbg = Entry(controls)

turtcL  = Label(controls, text="Turtle colour:")
turtcol = Entry(controls)
setCol  = Button(controls, text="Set colours",command=lambda:      

fractalL = Label(controls, text="Order of Fractal:")
fractorder = Entry(controls)

drawButton = Button(controls, text="Draw", command=lambda: draw(100, turtles, 80))

# now, arrange them on the screen
colourL.grid(row=1, column=1)
colourbg.grid(row=1, column=2, sticky="ew"
turtcL.grid(row=2, column=1)
turtcol.grid(row=2, column=2, sticky="ew")
setCol.grid(row=2, column=3)
drawButton.grid(row=3, column=1)
fractalL.grid(row=5, column=2)
fractorder.grid(row=6, column=2, sticky="ew")
...

最后,在使用grid时,您应该始终至少给出一列和一行正#34;重量"。这告诉tkinter在将小部件放置到位之后在哪里给出任何额外的空间。

假设您希望所有按钮位于顶部,您可以给第7行(最后一行小部件之后的行)一个正权重。此外,假设您希望包含条目的列尽可能宽,您可以为第2列提供权重:

controls.grid_rowconfigure(7, weight=1)
controls.grid_columnconfigure(2, weight=1)
相关问题