Tkinter网格方法

时间:2016-09-13 13:57:32

标签: python tkinter

我正在使用Tkinter为基于隐写术的计算机科学课程创建GUI。我正在窗口中的小部件上使用.grid()函数来展示它们,但是我无法通过这个特定的部分来了解我想要的内容。

以下是我目前的GUI:http://imgur.com/LNEZtEL (或只是有错误的部分)。

我希望剩余的字符标签直接位于文本输入框的下方,但由于某种原因,第4行在框下面开始大幅下降。如果我用西北方向锚定的列和行标记GUI,它看起来像这样:http://imgur.com/a/V7dTW

如果我缩小左侧的图像框,它看起来像我想要的,但我不希望图像这么小:http://imgur.com/a/0Dudu

图像框的行数为2,那么是什么导致第4行从文本输入框开始如此低?这大致是我希望GUI看起来像:http://imgur.com/a/ck04A

完整代码:

imageButton = Button(root, text="Add Image", command = add_image)
imageButton.grid(row = 2, columnspan = 2, sticky = W, padx = 30, pady = 20)
steg_widgets.append(imageButton)

image = Image.open("square.jpg")
image = image.resize((250,250))
photo = ImageTk.PhotoImage(image)
pictureLabel = Label(root, image = photo)
pictureLabel.image = photo
pictureLabel.grid(column = 0, row = 3, columnspan = 2, rowspan = 2, padx = 20, pady = (0, 20), sticky = NW)
steg_widgets.append(pictureLabel)

nameLabel = Label(root, text = "Brandon Edwards - OCR Computer Science Coursework 2016/2017")
nameLabel.grid(row = 0, column = 2, columnspan = 2, padx = (0, 20), pady = 10)
steg_widgets.append(nameLabel)

inputTextLabel = Label(root, text = "Enter text:")
inputTextLabel.grid(row = 2, column = 2, sticky = W)
steg_widgets.append(inputTextLabel)

startButton = Button(root, text="Go!", command = start_stega)
startButton.grid(row = 2, column = 2, sticky = E)
steg_widgets.append(startButton)

inputTextBox = Text(root, height = 10, width = 30)
inputTextBox.grid(row = 3, column = 2, sticky = NW)
steg_widgets.append(inputTextBox)

maxCharLabel = Label(root, text = "Remaining characters:")
maxCharLabel.grid(row = 4, column = 2, sticky = NW)
steg_widgets.append(maxCharLabel)

saveButton = Button(root, text="Save Image", command = save_image)
saveButton.grid(row = 2, column = 3, sticky = W)
steg_widgets.append(saveButton)

1 个答案:

答案 0 :(得分:1)

我建议将您的UI分解为逻辑部分,并分别布置每个部分。

例如,您显然有两个不同的部分:左侧的图像和按钮,右侧的其他小部件。首先为这两个组创建容器:

import Tkinter as tk
...
left_side = tk.Frame(root)
right_side = tk.Frame(root)

由于它们是并排的,pack是最简单的解决方法:

left_side.pack(side="left", fill="y", expand=False)
right_side.pack(side="right", fill="both", expand=True)

接下来,您可以专注于一方。您可以使用packgrid。这用grid用于说明目的:

image = tk.Canvas(left_side, ...)
button = tk.Button(left_side, ...)

left_side.grid_rowconfigure(0, weight=1)
left_side.grid_columnconfigure(0, weight=1)
image.grid(row=0, column=0, sticky="nw")
button.grid(row=1, column=0, sticky="n")

最后,在右侧工作。由于小部件从上到下堆叠,pack是自然选择:

l1 = tk.Label(right_side, text="Enter text:")
l2 = tk.Label(right_side, text="Remaining characters")
text = tk.Text(right_side)
l1.pack(side="top", fill="x")
text.pack(side="top", fill="both", expand=True)
l2.pack(side="top", fill="x")
相关问题