【问题标题】:Is there any way to stop a 'tkinter's mainloop' thread in python?有什么方法可以停止 python 中的 'tkinter's mainloop' 线程?
【发布时间】:2021-03-04 16:33:51
【问题描述】:

我是 GUI 编程的新手,我想在我的程序中创建一个简单的等待屏幕,我尝试过,这就是我的想法。问题是即使进程 func 终止,进程“func”的等待屏幕也不会停止。有没有办法停止线程't',或者有更好的解决方案?

from threading import Thread
from tkinter import *
from tkinter.ttk import Progressbar
from tkinter import ttk

def func():
    t = Thread(target = waiting).start()
    for i in range(1000):
        print(i)
    #myProgress.stop()



def waiting():
    root = Tk()
    root.geometry('400x250')

    myProgress = ttk.Progressbar(root ,orient =  HORIZONTAL, length = 200 , mode = 'determinate' )
    myProgress.pack(pady = 50)

    #myButton = Button(root , text = ' Button ' , command = func).pack()
    myProgress.start(10)
    root.mainloop()

func()

【问题讨论】:

  • 这能回答你的问题吗? How to stop a looping thread in Python?
  • 你不应该在线程中运行mainloop()
  • @YeeHaw 几乎所有的答案都有一个函数线程,他们需要做的就是使用布尔值或条件停止函数的循环。但在 Tkinter 的主循环中,我没有找到办法。
  • @acw1668 有没有其他办法解决这个问题???

标签: python multithreading tkinter


【解决方案1】:

您不应该通过杀死线程或其他方式来“停止”线程。它应该从函数中自行停止,例如使用变量stop_threads。例如,如果 var 是 True 让我们停止线程。代码:

import threading 
import time 
  
def run(): 
    while True: 
        print('thread running') 
        global stop_threads 
        if stop_threads: 
            break
  
stop_threads = False
t1 = threading.Thread(target = run) 
t1.start() 
time.sleep(1) 
stop_threads = True
t1.join() 
print('thread killed') 

【讨论】:

    猜你喜欢
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多