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

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.

主站蜘蛛池模板: 北宁市| 睢宁县| 潮州市| 三亚市| 留坝县| 安新县| 莱西市| 东城区| 安宁市| 绥化市| 德阳市| 织金县| 玉树县| 山西省| 宁南县| 淮北市| 开封县| 梁河县| 栾川县| 武陟县| 潢川县| 四子王旗| 宜君县| 云南省| 嘉禾县| 新平| 通州市| 清镇市| 全椒县| 红原县| 十堰市| 唐河县| 南康市| 台州市| 无为县| 嘉禾县| 安阳市| 民丰县| 息烽县| 巴彦淖尔市| 小金县|