|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
请问像这样一个代码,点了“函数停止运行”之后,再次点击“主函数”,只执行一次就停了,请问是什么问题呢?
这是原帖,谢谢!!
https://fishc.com.cn/thread-174101-1-1.html
- from threading import Thread
- import tkinter as tk
- from time import sleep # 这个可以去掉,只是测试时候速度慢点否则程序一下运行完都还来不及点终止
- root=tk.Tk()
- def mainfunction():
- def func():
- for i in range(10000):
- sleep(0.5) # 这个可以去掉
- print ("第{0}步已完成".format(i))
- if stop_mainfunction:
- print('函数停止运行')
- break
- global t
- t = Thread(target=func)
- t.setDaemon(True)
- t.start()
- def stop():
- global stop_mainfunction
- stop_mainfunction = True
- button1=tk.Button(root,text='主函数',command=mainfunction)
- button1.pack()
- stop_mainfunction = False
- stop_button = tk.Button(root,text='终止函数运行',command=stop)
- stop_button.pack()
- root.mainloop()
复制代码
本帖最后由 isdkz 于 2022-2-18 22:13 编辑
因为你的 stop_mainfunction 还没有赋值回 False,依然是 True
- from threading import Thread
- import tkinter as tk
- from time import sleep # 这个可以去掉,只是测试时候速度慢点否则程序一下运行完都还来不及点终止
- root=tk.Tk()
- def mainfunction():
- global stop_mainfunction # 加上这行
- stop_mainfunction = False # 加上这行
- def func():
- for i in range(10000):
- sleep(0.5) # 这个可以去掉
- print ("第{0}步已完成".format(i))
- if stop_mainfunction:
- print('函数停止运行')
- break
- global t
- t = Thread(target=func)
- t.setDaemon(True)
- t.start()
- def stop():
- global stop_mainfunction
- stop_mainfunction = True
- button1=tk.Button(root,text='主函数',command=mainfunction)
- button1.pack()
- # stop_mainfunction = False 去掉这行
- stop_button = tk.Button(root,text='终止函数运行',command=stop)
- stop_button.pack()
- root.mainloop()
复制代码
|
|