我想要做的是,在Entry小部件中键入一些单词,同时更改标签小部件中显示的字符。以下是代码:
import tkinter as tk
class App(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.entry = tk.Entry(master=self)
self.entry.pack(side="left")
self.var = tk.StringVar()
self.var.set(self.entry.get)
self.label = tk.Label(master=self)
self.label.pack(side="left")
self.configure_widgets()
self.pack()
def configure_widgets(self):
self.label.configure(textvariable=self.var)
if __name__ == "__main__":
root = tk.Tk()
example = App(master=root)
example.mainloop()
我应该更改代码的哪些部分?提前谢谢。
答案 0 :(得分:1)
Entry
和Label
都接受变量作为参数。该条目将设置变量值,Label将获得它。
import tkinter as tk
class App(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.var = tk.StringVar()
self.entry = tk.Entry(master=self, textvariable=self.var)
self.entry.pack(side="left")
self.label = tk.Label(master=self, textvariable=self.var)
self.label.pack(side="left")
self.configure_widgets()
self.pack()
def configure_widgets(self):
self.label.configure(textvariable=self.var)
if __name__ == "__main__":
root = tk.Tk()
example = App(master=root)
example.mainloop()