2 '''Button按钮 点击执行对应的命令''' 3 import tkinter as tk 4 #初始化窗口 5 window = tk.Tk() 6 #窗口名称 7 window.title("My Window") 8 #窗口大小,是 x 不是 * 9 window.geometry("400x400") 10 #创建对象num,用来计数 11 num = 0 12 label = tk.Label(window,text="Hello World",height=2,width=20,fg="green") 13 label.pack() 14 def hit_me(): 15 #使用全局变量 16 global num 17 num = num + 1 18 text = "you hit " + str(num) 19 #配置label的属性 20 label.config(text=text) 21 def forget_button(): 22 button.forget() 23 # 创建按钮,这里的command是调用事件 24 def b_pack(): 25 button.pack() 26 button = tk.Button(window,text="hit_me",fg="red",command=hit_me) 27 button.pack() 28 # 使button不可显示 29 b_forget = tk.Button(window,text="forget_button",command=forget_button) 30 b_forget.pack() 31 # 再次使button显示 32 button_p = tk.Button(window,text="button_pack",command=b_pack).pack() 33 # 循环窗口 34 window.mainloop()