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

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.

主站蜘蛛池模板: 祁阳县| 镇康县| 佛学| 宁河县| 南乐县| 屏山县| 西畴县| 蓝田县| 石嘴山市| 敖汉旗| 射阳县| 临安市| 鹿邑县| 仙桃市| 张家港市| 金乡县| 门源| 喀喇沁旗| 浑源县| 大方县| 洛阳市| 肇东市| 古交市| 鄄城县| 天镇县| 平顶山市| 斗六市| 麻江县| 左权县| 观塘区| 武威市| 阿拉善左旗| 杂多县| 乐亭县| 景德镇市| 特克斯县| 中方县| 汾西县| 乐安县| 旅游| 扎兰屯市|