使用PyGubu(创建Tkinter接口的工具)我获得了以下GUI:
当我点击“创建”按钮时,一个函数被调用。这个函数需要相当长的时间,图形界面只是冻结。由于我希望尽可能地将图形界面和功能部分分开,所以我不想从我调用的函数中更新进度条或界面
对我来说,最好的情况是没有线程的解决方案:我希望在单击“创建”时,我的函数运行,而进度条会自动更新(只是向用户显示反馈,并告诉他“看,我正在做某事”),并且界面保持响应,因此,用户可以在函数完成时与它进行交互
我尝试使用线程解决此问题:
#I have this code in my main.py:
from threading import Thread
from queue import Queue, Empty
my_queue=Queue()
#And this is a simplified version of the Command of the "Create" Button:
def create_command(self):
#Show the progress bar and start it
self.show_item(self.progress)
self.progress.start()
#Run the big function
thrd = Thread(target = my_big_function, args=(some_arguments, my_queue))
thrd.start()
do_retry = True
while do_retry: #Repeat until you have a result
try:
result = my_queue.get(False) #If you have a result, exit loop. Else, throw Empty
do_retry = False
except Empty: #Queue is still empty
self.progress_var.set(self.progress_var.get()+1)
sleep(0.05)
self.mainwindow.update() #Update the progress bar
q.task_done()
self.progress.stop()
由于我不习惯使用线程,我面临两个问题:
在一些运行中(不是所有的,只是一些),我有一个运行时错误
运行时错误:主线程不在主循环中 我试图通过查看StackOverflow中的其他问题来克服这个问题,但现在它只是随机发生的,我不知道如何避免它。Python3.x不再维护模块mtTinker(有一个模糊的尝试,充满了待办事项和血液)
如果大函数中存在某种异常,我不知道如何处理它。程序将永远运行,等待永远不会返回的结果
我怎样才能获得我想要的结果?提前谢谢
您可以尝试将
root.update()
添加到您调用的函数中,即主循环中。希望对你有帮助相关问题 更多 >
编程相关推荐