设计:
要解决您的问题,您需要设计这个简单的解决方案:
- 使用
get() 方法检索Tkinter.Entry 小部件的文本。
- 使用
append() 方法将您在1 中获得的文本添加到Main_Q。
- 使用
command 方法绑定单击Main_Q 和您的GUI 时更新的按钮。
- 创建一个新的 Tkinter.Label 小部件,将其文本设置为您在 1 中获得的值,并在 GUI 中增加其对应的行。
我更喜欢将您的代码组织在一个包含构造函数的类中,在该构造函数中初始化 Main_Q,以便我们调用 initialize_user_interface() 来使用它的三个元素初始化 GUI:
def __init__(self, parent):
Tkinter.Frame.__init__(self, parent)
self.parent = parent
self.Main_Q = ["read", "clean dishes", "wash car"]
self.r = 0 # position of the row of each label
self.initialize_user_interface()
initialize_user_interface() 方法正如其名。我们主要绑定函数update_gui(),它使用command = self.update_gui插入一个新标签,并将文本设置为用户在Tkinter.Entry小部件中键入的内容command = self.update_gui
ef initialize_user_interface(self):
self.parent.title("Update GUI")
self.parent.grid_rowconfigure(0, weight = 1)
self.parent.grid_columnconfigure(0, weight = 1)
for e in self.Main_Q:
Tkinter.Label(self.parent, anchor = Tkinter.W, text = e).grid(row = self.r, sticky = Tkinter.W)
self.r+=1
self.entry_text = Tkinter.Entry(self.parent)
self.entry_text.grid(row = 0, column = 1)
self.button_update = Tkinter.Button(self.parent, text = "Update", command = self.update_gui).grid(row = 1, column = 1, sticky = Tkinter.E)
最后,没有什么比update_gui()函数更简单了:
def update_gui(self):
self.r+=1 # increment the row reserved to the new label
self.Main_Q.append(self.entry_text.get())
Tkinter.Label(self.parent, anchor = Tkinter.W, text = self.entry_text.get()).grid(row = self.r, sticky = Tkinter.W)
对应用程序进行编程:
这是完整的程序:
'''
Created on Mar 11, 2016
@author: Bill BEGUERADJ
'''
import Tkinter
class Begueradj(Tkinter.Frame):
def __init__(self, parent):
Tkinter.Frame.__init__(self, parent)
self.parent = parent
self.main_queue = ["read", "clean dishes", "wash car"]
self.r = 0
self.initialize_user_interface()
def initialize_user_interface(self):
self.parent.title("Update GUI")
self.parent.grid_rowconfigure(0, weight = 1)
self.parent.grid_columnconfigure(0, weight = 1)
for e in self.main_queue:
Tkinter.Label(self.parent, anchor = Tkinter.W, text = e).grid(row = self.r, sticky = Tkinter.W)
self.r+=1
self.entry_text = Tkinter.Entry(self.parent)
self.entry_text.grid(row = 0, column = 1)
self.button_update = Tkinter.Button(self.parent, text = "Update", command = self.update_gui).grid(row = 1, column = 1, sticky = Tkinter.E)
def update_gui(self):
self.r+=1
self.main_queue.append(self.entry_text.get())
Tkinter.Label(self.parent, anchor = Tkinter.W, text = self.entry_text.get()).grid(row = self.r, sticky = Tkinter.W)
def main():
root = Tkinter.Tk()
b = Begueradj(root)
root.mainloop()
if __name__ == "__main__":
main()
演示:
下面是运行程序的截图:
注意:
我使用 Python 2.7 编写了之前的程序,所以如果你想测试它,请将 Tkinter 更改为 tkinter。其他一切都保持不变。