上面的结构是“标签+入口+标签+间距+标签”。为了确保小部件左对齐,我使用了以下代码:
phraseLabel1 = tk.Label(questionFrame)
phraseLabel1.pack(side=tk.LEFT)
keyWordEntry = tk.Entry(questionFrame)
keyWordEntry.pack(side=tk.LEFT)
phraseLabel2 = tk.Label(questionFrame)
phraseLabel2.pack(side=tk.LEFT)
keyWordLabel = tk.Label(questionFrame)
keyWordLabel.pack(side=tk.LEFT,padx=30)
我的目标是为用户提供多个句子的输入屏幕。例如,如下图所示:
虽然我设法通过底层(实验)代码创建标签,但我对管理几何图形缺乏了解。
root = tk.Tk()
root.title("myTest")
root.geometry("700x700")
questionFrame = tk.Frame(root)
resultFrame = tk.Frame(root)
for frame in (questionFrame, resultFrame):
frame.grid(row=0, column=0, sticky='news')
#DB Query returning a set of phrases and Keywords
(zinPhrase1, zinPhrase2, keyWordFR, keyWordNL)=getPhrase()
#Init
lab1 = []
keyWordEntry = []
lab2 = []
keyWord = []
for i in range(4): #4 is entered as a dummy value
lab1.append(tk.Label(questionFrame))
lab1[i].pack()
keyWordEntry.append(tk.Entry(questionFrame))
keyWordEntry[i].pack()
lab2.append(tk.Label(questionFrame))
lab2[i].pack()
keyWord.append(tk.Label(questionFrame))
keyWord[i].pack()
lab1[i].config(text=zinPhrase1[i])
keyWordEntry[i].config(width=8)
lab2[i].config(text=zinPhrase2[i])
keyWord[i].config(text=keyWordNL[i],fg="red")
questionFrame.tkraise()
root.mainloop()
如何逐行管理小部件的位置,如上图所示?任何帮助都会感激不尽。
答案 0 :(得分:3)
由于您似乎不想在网格中组织小部件,因此解决此问题的最常见方法是为每行创建一个框架。框架从上到下堆叠,框架内的小部件从左到右堆叠。
根据我的经验,当您将小部件创建与小部件布局分开时,GUI代码更容易可视化,因此我在下面的示例中已经完成了这一操作,希望能够更容易理解。
for i in range(4): #4 is entered as a dummy value
rowFrame = tk.Frame(questionFrame)
rowFrame.pack(side="top", fill="x")
lab1.append(tk.Label(rowFrame))
keyWordEntry.append(tk.Entry(rowFrame))
lab2.append(tk.Label(rowFrame))
keyWord.append(tk.Label(rowFrame))
lab1[i].pack(side="left")
keyWordEntry[i].pack(side="left")
lab2[i].pack(side="left", padx=(0, 40))
keyWord[i].pack(side="left")
lab1[i].config(text=zinPhrase1[i])
keyWordEntry[i].config(width=8)
lab2[i].config(text=zinPhrase2[i])
keyWord[i].config(text=keyWordNL[i],fg="red")
上面的代码结果如下:
答案 1 :(得分:2)
以下是否足够?
for i in range(4): #4 is entered as a dummy value
frames.append(tk.Frame(questionFrame))
frames[i].grid(row=i, column=0, stick='W')
for i in range(4):
lab1.append(tk.Label(frames[i]))
lab1[i].grid(row=0, column=0)
keyWordEntry.append(tk.Entry(frames[i]))
keyWordEntry[i].grid(row=0, column=1)
lab2.append(tk.Label(frames[i]))
lab2[i].grid(row=0, column=2)
keyWord.append(tk.Label(frames[i]))
keyWord[i].grid(row=0, column=3)
lab1[i].config(text=zinPhrase1[i])
keyWordEntry[i].config(width=8)
lab2[i].config(text=zinPhrase2[i])
keyWord[i].config(text=keyWordNL[i],fg="red")