Python 3.x 在Python3中,如何在单击按钮时停止函数的执行?
我正在用tkinter按钮制作一个小型GUI应用程序,当单击按钮1时,一个具有无限循环运行的函数 我想有可能停止另一个按钮的进程,并重置应用程序的初始状态。我不知道怎么做,因为当button1启动脚本时,button2被阻止。我想在按钮2单击时停止执行函数1。这是我的密码Python 3.x 在Python3中,如何在单击按钮时停止函数的执行?,python-3.x,tkinter,Python 3.x,Tkinter,我正在用tkinter按钮制作一个小型GUI应用程序,当单击按钮1时,一个具有无限循环运行的函数 我想有可能停止另一个按钮的进程,并重置应用程序的初始状态。我不知道怎么做,因为当button1启动脚本时,button2被阻止。我想在按钮2单击时停止执行函数1。这是我的密码 from tkinter import * root = Tk() def function1(): x =0 while True : # infinite loop print(x) x = x
from tkinter import *
root = Tk()
def function1():
x =0
while True : # infinite loop
print(x)
x = x + 1
def function2():
sys.exit()
btn1 = Button(root, text ="Button 1", command = function1)
btn1.place(x=200, y=200)
btn2 = Button(root, text ="Button 2", command = function2)
btn2.place(x= 300,y=300)
root.geometry("400x400")
mainloop()
谢谢。您不能在按钮中运行无限循环,而是可以使用递归。可以递归调用函数,
function1、function2
可以是用于控制任何变量的函数。请通过以下代码:
from tkinter import *
running = False
x=0
def scanning():
global x
if running:
x = x+1
print (x)
# After 10 milli second, call scanning again (create a recursive loop)
root.after(10, scanning)
def start():
global running
running = True
def stop():
global running
running = False
root = Tk()
root.title("Continuous Loop")
root.geometry("100x100")
app = Frame(root)
app.grid()
start = Button(app, text="Start counting", command=start)
stop = Button(app, text="Stop counting", command=stop)
start.grid()
stop.grid()
root.after(1000, scanning) # After 1 second, call scanning
root.mainloop()
希望这会有所帮助。谢谢。但当代码是其他东西时,比如某个文件读取发生在按钮ckick上,我们希望它在单击另一个按钮时突然停止。这就像我想停止执行一个函数,不管它里面发生了什么,只要点击一个按钮就进入初始状态。您提供的代码仅适用于此问题。但是,我希望tkinter窗口中的所有按钮始终处于活动状态,而不考虑时间因素。