[Tutor] Dynamic variables changed via Tkinter button
Alan Gauld
alan.gauld at yahoo.co.uk
Thu Apr 16 07:53:49 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.
Here is some runnable code that illustrates what you want, i think...
import tkinter as tk
class App():
def __init__(self,parent):
self.main = tk.Frame(parent)
self.main.pack()
self.state='idle'
self.count = 0
self.lbl = tk.Label(self.main, text="Count = 0")
self.lbl.pack()
self.btn = tk.Button(self.main, text="Press & Hold")
self.btn.pack()
self.btn.bind('<Button-1>', self.press)
self.btn.bind("<ButtonRelease-1>", self.stop)
def press(self,evt):
self.state='working'
self.btn.after(100,self.update)
def update(self):
self.count += 0.1
self.lbl['text'] = "Count = %f" % self.count
self.main.update_idletasks()
if self.state == 'working':
self.btn.after(100, self.update)
def stop(self,evt):
self.state = 'idle'
top = tk.Tk()
app = App(top)
top.mainloop()
--
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