Reputation: 155
Ive been trying to make a program with 2 buttons, pressing one of them will start an infinite loop and pressing the other one will stop it.
All the methods ive tried will just pause the loop.
from Tkinter import *
import time
s = 0
def stopit():
s = 1
print "stoped"
#
def callback():
if s == 0:
while True:
print "called the callback!"
time.sleep(3)
if s == 1:
break
#
#
#
#
root = Tk()
def main():
# create a menu
menu = Menu(root)
root.config(menu=menu)
b = Button(root, command=stopit)
b.pack()
filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="New", command=callback)
filemenu.add_command(label="Open...", command=callback)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=callback)
helpmenu = Menu(menu)
menu.add_cascade(label="Help", menu=helpmenu)
helpmenu.add_command(label="About...", command=callback)
mainloop()
time.sleep(3)
#
main()
Upvotes: 1
Views: 5275
Reputation: 82889
There are two problems with your code:
callback
method never finishes (due to the infinite loop), causing the GUI to freeze. Instead, use the after
method to schedule another execution of callback
after the method finishes.stopit
method creates a local variable s
instead of changing the global one. Use the global
keyword to fix this.Change the two methods to something like this, and it should work:
def stopit():
global s
s = 1
print "stopped"
def callback():
if s == 0:
print "called the callback!"
root.after(3000, callback)
Upvotes: 2