python - 如何在子线程中更新父类对象(self.progress)?
问题描述
我正在尝试运行进度状态栏来向用户发出正在执行任务的信号。我尝试了不同的策略但没有成功。
在这段代码中,问题是我无法从子线程更新进度条的值。我做错了什么。
import time
import threading
from tkinter import Tk, Button
from tkinter.ttk import Progressbar
class App():
def __init__(self, root):
self.button = Button(root)
self.button.grid(row=1,column=0, padx=2,pady=2);
self._resetbutton()
self.progress = Progressbar(root, length=330, mode = 'determinate')
self.progress.grid( row=2,column=0, columnspan=4,padx=2,pady=2);
def _resetbutton(self):
self.running = False
self.button.config(text="Start", command=self.startthread)
def startthread(self):
self.running = True
newthread = threading.Thread(target=self.status_bar)
newthread.start()
self.button.config(text="Stop", command=self._resetbutton)
for x in range(12):
time.sleep(.75)
print(".");
def status_bar( self ):
value = 0;
print("started thread");
while self.running:
value = ( value + 10 ) % 100;
#self.progress['value'] = value; # <-- failure
time.sleep(0.5);
print( value );
print("done thread");
ventana_principal=Tk()
calculadora=App(ventana_principal)
ventana_principal.mainloop()
解决方案
在这里,您可以看到 startthread 函数中的更改以使此进度条正常工作。
def startthread(self):
def status_bar( ):
value = 0;
print("started thread");
while self.running:
value = ( value + 10 ) % 100;
self.progress['value'] = value; # <-- failure
time.sleep(0.5);
print( value );
print("done thread");
def aux_func( ):
while self.running:
time.sleep(.75)
print(".");
self.running = True
newthread = threading.Thread(target=status_bar)
newthread.start()
newthread2 = threading.Thread(target=aux_func)
newthread2.start()
self.button.config(text="Stop", command=self._resetbutton)
推荐阅读
- java - 如何在Java中旋转以空格分隔的整数字符串?
- python - 跨类的多个实例仅调用一次函数
- tkinter - 如何在 Tkinter 中更改按钮文本的大小
- docker - 编辑了如何在 docker 中使 nginx pont 连接到我的 mosquitto 代理
- react-native - 如何使用 react-navigation 重置到不同堆栈中的屏幕?
- java - Selenium:AbstractMethod 错误启动 GeckoDriver createArgs()
- iis - 无法正常关闭应用程序(IIS 挂起)
- python - 运行程序时如何保持 Selenium Webdriver chrome 浏览器打开?
- javascript - 下载并使用 javascript 执行
- reactjs - 如何更改 React 中的输入字段值?