官术网_书友最值得收藏!

Our first try

Let's give it a try the regular way. Open up your previous code and change it to look like this:

class Window(tk.Tk):
def __init__(self):
super().__init__()
self.title("Hello Tkinter")
self.label_text = "Choose One"

self.label = tk.Label(self, text=self.label_text)
self.label.pack(fill=tk.BOTH, expand=1, padx=100, pady=30)

hello_button = tk.Button(self, text="Say Hello",
command=self.say_hello)
hello_button.pack(side=tk.LEFT, padx=(20, 0), pady=(0, 20))

goodbye_button = tk.Button(self, text="Say Goodbye",
command=self.say_goodbye)
goodbye_button.pack(side=tk.RIGHT, padx=(0, 20), pady=(0, 20))

def say_hello(self):
self.label_text = "Hello World"

def say_goodbye(self):
self.label_text="Goodbye! \n (Closing in 2 seconds)"
self.after(2000, self.destroy)


if __name__ == "__main__":
window = Window()
window.mainloop()

Give this code a whirl and click on your Say Hello button. Nothing happens. Now try your Say Goodbye button. The label will not update, but the window will still close after 2 seconds. This goes to show that the code written is not invalid, but will not behave as we may expect it to.

主站蜘蛛池模板: 乾安县| 吐鲁番市| 麟游县| 德州市| 雅江县| 新疆| 盐边县| 汾阳市| 衢州市| 晋江市| 栾川县| 郧西县| 长丰县| 永嘉县| 孙吴县| 涟水县| 濮阳县| 绥芬河市| 敦煌市| 元谋县| 垦利县| 青海省| 象州县| 佳木斯市| 荥经县| 安图县| 石泉县| 溧水县| 利津县| 景洪市| 台湾省| 五指山市| 旬邑县| 乌鲁木齐县| 麟游县| 长顺县| 清原| 紫云| 阜康市| 赤城县| 秦皇岛市|