Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function whenever global variable changes it value?

Tags:

python

tkinter

How can I call a function change_label whenever global variable a changes its value? With change_variable I am trying to simulate actual changing of the variable (the variable changes on button click).

from tkinter import *

a = 3

class Application(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.master = master
        self.button = Button(self.master, text='Change Variable', command=self.change_variable)
        self.button.grid(row=0)
        self.label = Label(self.master, text='Test')
        self.label.grid(row=1)

    def change_label(self):
        self.label.config(bg='Red', fg='Yellow')

    def change_variable(self):
        global a
        a = 1

def main():
    root = Tk()
    Application(root)
    root.mainloop()

if __name__ == '__main__':
    main()
like image 809
nuked0ne Avatar asked Jul 04 '26 15:07

nuked0ne


1 Answers

If you use one of tkinters special variables (StringVar, etc) you can add a "trace" that will trigger a callback whenever the variable is set or unset.

For example:

class Application(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        ...
        self.a = tk.IntVar(value=3)
        self.a.trace("w", self.change_label)
        ...

    def change_label(self, *args):
        self.label.config(bg='Red', fg='Yellow')

    def change_variable(self):
        self.a.set(1)

With that, whenever you set the value of self.a via the set method, the function bound with the trace will be called.

Any widget that uses that variable also will be updated. For example, change your label to this:

self.label = tk.Label(self.master, textvariable=self.a)

When you click the button, notice that the label changes to reflect the change.

For a description of what arguments are passed to the trace function, see What are the arguments to Tkinter variable trace method callbacks?

These variables have a good description here: The Variable Classes (BooleanVar, DoubleVar, IntVar, StringVar)

like image 175
Bryan Oakley Avatar answered Jul 07 '26 05:07

Bryan Oakley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!