python - How to stop a running function without exiting the Tkinter window entirely? -


i'm using python 2.7, , i'm trying write gui, having issues buttons. have running properly, assuming i've made mistake inputs or something, i'd way stop running function after hitting "go" button. code way long post here, simple example below. how make "stop" button break start function, not quit window entirely? maybe threading?

i'm sort of new writing guis, , i'm not programmer, isn't area of expertise.

the gui totally unresponsive while main function running. there must way simultaneously run function while allowing me change things in gui , hit buttons, i'm not sure how works. updates don't have implemented until next time "go" button hit though.

import time tkinter import *   class example:     def __init__(self,master):         self.startbutton = button(master,text='start',command=self.start)         self.startbutton.grid(row=0,column=0)          self.stopbutton = button(master,text='stop',command=self.stop)         self.stopbutton.grid(row=0,column=1)          self.textbox = text(master,bd=2)         self.textbox.grid(row=1,columnspan=2)      def start(self):         self.textbox.delete(0.0,end)         in xrange(1000):             text = i+1             self.textbox.insert(end,str(text)+'\n\n')             time.sleep(1)         return      def stop(self):         """ here stop running "start" function """         pass   root=tk() example(root) root.mainloop() 

with tkinter, such things commonly done using universal widget after() method. should not use time.sleep() in tkinter program because prevents mainloop() running (which making gui unresponsive in code).

a successful after() call return integer "cancel id" can used stop callback scheduled. what's needed stop() method of example class stop method doing counting.

from tkinter import *  class example:     def __init__(self, master):         self.startbutton = button(master,text='start', command=self.start)         self.startbutton.grid(row=0, column=0)          self.stopbutton = button(master, text='stop', command=self.stop)         self.stopbutton.grid(row=0, column=1)          self.textbox = text(master, bd=2)         self.textbox.grid(row=1, columnspan=2)      def start(self):         self.count = 0         self.cancel_id = none         self.counter()      def counter(self):         self.textbox.delete("1.0", end)         if self.count < 10:             self.count += 1             self.textbox.insert(end, str(self.count)+'\n\n')             self.cancel_id = self.textbox.after(1000, self.counter)      def stop(self):         if self.cancel_id not none:             self.textbox.after_cancel(self.cancel_id)             self.cancel_id = none  root=tk() example(root) root.mainloop() 

Comments

Popular posts from this blog

Android : Making Listview full screen -

javascript - Parse JSON from the body of the POST -

javascript - Chrome Extension: Interacting with iframe embedded within popup -