[Tutor] Dynamic variables changed via Tkinter button

Alan Gauld alan.gauld at yahoo.co.uk
Thu Apr 16 05:28:48 EDT 2020


On 15/04/2020 21:09, Jon Davies wrote:

> I need to implement two labels (displaying dynamic variables) that will change based on a button being held.

Working on the basis of a button being held is not normal GUI behaviour
so you won;t find any standard events to deal with that. Instead you
will need to look for mouse button events on the button.

So when the button is first pressed you need to start a pseudo
loop which performs the calculation and then pauses briefly
 - say for 50ms - then repeats until the mouse button up is
received.


So in your code you need to
1) bind the <ButtonPressed-1> and <ButtonRelease-1> events to your GUI
Button
2) On ButtonPressed set a state value of "fuelling"(or whatever you call
it)) Note this is a local state value in your Fuelling view, this is not
in the application level states table.(although it could be if you want.)
3) Start a loop using the after() method that checks the state for
fuelling and updates the label and then repeats the after() call.
If the state is not fuelling it updates the label and does not repeat
but calls your controller.setState() method to navigate to the
appropriate screen.
4) On ButtonReleased you change that state from "fuelling"

I think that is what you are trying to achieve...

So in pseudo code:

class Fuellingscreen(tk.Frame):
   def __init__(self,controller):
       ....
       self.fuelButton.bind(<ButtonPressed-1>, self.beginFuelling)
       self.fuelbutton.bind(<ButtonRelease-1>, self.endFuelling)
       set.state = 'idle'
       ...
   def beginFuelling(self):
       set label
       set self.state = 'fuelling'
       ... anything else....
       self.after(50,self.updateFuel)

   def updateFuel(self):
       do calculation
       update label
       self.update_idletasks()   # forces redraw of GUI
       if self.state == 'fuelling':
          self.after(50,self.updateFuel) #go again

   def endFuelling(self):
       self.state = 'idle'

Hopefully that's enough to get you started

BTW I didn't check the event names so you may need to look them up.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list