如何修改Tkinter线程化进度条示例的窗口标题为“progress”
修改Tkinter窗口标题为"progress"的方法
最简实现方式
窗口标题由Tkinter的主窗口实例(tk.Tk()对象)控制,直接在创建主窗口后添加一行代码即可:
ROOT = tk.Tk() ROOT.title("progress") # 设置窗口标题 APP = AppGUI(ROOT) ROOT.mainloop()
原代码的其他问题修正
原代码存在两处会导致程序异常的问题,需要一并修正:
- 类缩进错误:
AppGUI类被错误嵌套在printmsg函数内部,需要将其移到函数外部。 - 线程使用错误:
Progress类中的线程实现逻辑有误,ttk.Progressbar.start()本身是Tkinter的内置方法,不需要额外用线程包裹;且原线程初始化写法不符合Python线程规范。修正后去掉多余的线程代码,仅保留进度条的控制逻辑(如果需要在线程中执行耗时任务,应将任务放在线程的target参数中)。
修正后的完整代码
""" An example of the use of threading to allow simultaneous operations in a tkinter gui (which is locked to a single thread) """ import threading import tkinter as tk from tkinter import ttk class Progress(): """ threaded progress bar for tkinter gui """ def __init__(self,parent, row, column, columnspan): self.maximum = 100 self.interval = 10 self.progressbar = ttk.Progressbar(parent, orient=tk.HORIZONTAL, mode="indeterminate", maximum=self.maximum) self.progressbar.grid(row=row, column=column, columnspan=columnspan, sticky="we") # 修正:去掉错误的线程初始化,进度条start不需要额外线程 self.progressbar.start(self.interval) def pb_stop(self): """ stops the progress bar """ VALUE = self.progressbar["value"] self.progressbar.stop() self.progressbar["value"] = VALUE def pb_start(self): """ starts the progress bar """ VALUE = self.progressbar["value"] self.progressbar.configure(mode="indeterminate", maximum=self.maximum, value=VALUE) self.progressbar.start(self.interval) def pb_clear(self): """ stops the progress bar """ self.progressbar.stop() self.progressbar.configure(mode="determinate", value=0) def pb_complete(self): """ stops the progress bar and fills it """ self.progressbar.stop() self.progressbar.configure(mode="determinate", maximum=self.maximum, value=self.maximum) def printmsg(): """ prints a message in a seperate thread to tkinter """ print("proof a seperate thread is running") class AppGUI(tk.Frame): """ class to define tkinter GUI""" def __init__(self, parent,): tk.Frame.__init__(self, master=parent) prog_bar = Progress(parent, row=0, column=0, columnspan=2) # Button 1 start_button = ttk.Button(parent, text="start", command=prog_bar.pb_start) start_button.grid(row=1, column=0) # Button 2 stop_button = ttk.Button(parent, text="stop", command=prog_bar.pb_stop) stop_button.grid(row=1, column=1) # Button 3 complete_button = ttk.Button(parent, text="complete", command=prog_bar.pb_complete) complete_button.grid(row=2, column=0) # Button 4 clear_button = ttk.Button(parent, text="clear", command=prog_bar.pb_clear) clear_button.grid(row=2, column=1) # Button 5 test_print_button = ttk.Button(parent, text="thread test", command=printmsg) test_print_button.grid(row=3, column=0, columnspan=2, sticky="we") ROOT = tk.Tk() ROOT.title("progress") # 设置窗口标题 APP = AppGUI(ROOT) ROOT.mainloop()
内容的提问来源于stack exchange,提问作者TonyF
相关产品推荐
相关产品推荐

