Python GUI 编程 04 : 事件循环 Event Loop
import tkinter as tkfrom tkinter.messagebox import showerror,showinfo, showwarningfrom tkinter import ttk# 定义开始事件函数def start: btn.configure(text="Stop!", command=stop) # 将按钮功能重新绑定为停止事件函数 lbl["text"] = "Redo ..." global interrupt # 定义一个flag全局变量 interrupt=False root.after(1,step) # 主窗体1毫秒后执行step事件def stop: global interrupt # 同步全局变量 interrupt = Truedef step(count=0): pb["value"] = count if interrupt: # 事件循环过程若interrupt为True result(pb["value"]) # 调用result方法将进度条值传递到标签文本 return # 停止当前循环 root.after(100) #! 主程序100毫秒后执行下一行 if count == 50: #! 循环停止条件 result(pb["value"]) btn.configure(text="Start!", command=start) return lbl["text"] = f'Answer : {str(pb["value"])}' idx = root.after(1, lambda: step(count + 1)) # 主窗体1毫秒后再次运行回调函数step # print(idx)def result(value): # pb["value"]=0 btn.configure(text="Continue!", command=continue_) # interrupt为True时变更按钮文本及绑定方法 lbl["text"] = f"Answer {str(value)}" if value else "No Answer" # 传递代入参数到文本标签内容def continue_: global interrupt # 同步全局变量 interrupt = False step(pb["value"]) btn.configure(text="Stop", command=stop)root = tk.Tk# root.geometry(f"{root.winfo_screenwidth}x{root.winfo_screenheight}")# root.state(newstate="zoomed") # 最大化窗体f = ttk.Frame(root, width=150); f.gridbtn = ttk.Button(f, text="Start!", command=start)btn.grid(column=1, row=0, padx=5, pady=5)lbl = ttk.Label(f, width=20, text="No Answer")lbl.grid(column=0, row=0, padx=5, pady=5, sticky="we")pb = ttk.Progressbar(f, orient=tk.HORIZONTAL, mode="determinate", maximum=50)pb.grid(column=0, row=1, padx=5, pady=5, columnspan=2, sticky="we")# root.after_idle(showinfo(title="notice",message="No Event In Queue"))root.mainloop