Python & PyGTK: button click stop

I am working on programming some application, and I would like to create a while loop when the button is clicked, and if it clicks again to stop it. This is the code for the button:

self.btnThisOne = gtk.Button("This one") self.btnThisOne.connect("clicked", self.startLoop) 

The code for startLoop def will look like this:

 def startLoop(self): while self.btnThisOne?(is_clicked)?: #do something 

How to do it?

+4
source share
1 answer

Unfortunately, you cannot just use an unlimited while loop in the main thread of your application. This blocks the main gtk event loop and you will not be able to handle more events. What you probably want to do is create a thread.

Do you consider using ToggleButton instead of GtkButton ? The closest to the is_clicked method is is_active , and you will find it in the toggle buttons.

Here is an example of starting and controlling the flow depending on the state of the toggle button (replace triggered with clicked and ToggleButton with Button if you want to use a regular button):

 import gtk, gobject, threading, time gobject.threads_init() window = gtk.Window() button = gtk.ToggleButton('Start Thread') class T(threading.Thread): pause = threading.Event() stop = False def start(self, *args): super(T, self).start() def run(self): while not self.stop: self.pause.wait() gobject.idle_add(self.rungui) time.sleep(0.1) def rungui(self): pass # all gui interaction should happen here thread = T() def toggle_thread(*args): if not thread.is_alive(): thread.start() thread.pause.set() button.set_label('Pause Thread') return if thread.pause.is_set(): thread.pause.clear() button.set_label('Resume Thread') else: thread.pause.set() button.set_label('Pause Thread') button.connect('toggled', toggle_thread, None) window.add(button) button.show() window.show() gtk.main() 

This PyGTK FAQ request may be helpful. Greetings.

+3
source

Source: https://habr.com/ru/post/1442592/


All Articles