0

I'm new to Python, and I don't know how to set a variable only once and then change it dynamically. Here is an example:

from tkinter import *
bt_text = "A"

root = Tk()

def switcher():
    print(bt_text)
    if bt_text == "A":
        bt_text = "B"
    else:
        bt_text = "A"



b=Button(root, justify = LEFT, command=switcher)
photo1=PhotoImage(file="background.gif")
b.config(image=photo1,text=bt_text, compound="center", width="50",height="20",borderwidth="0")
b.grid(row=2, column=0)

root.mainloop()

Why do I get an error?

UnboundLocalError: local variable 'bt_text' referenced before assignment

And why does the error not appear in this case:

from tkinter import *
bt_text = "A"

root = Tk()

def switcher():
    print(bt_text)

b=Button(root, justify = LEFT, command=switcher)
photo1=PhotoImage(file="background.gif")
b.config(image=photo1,text=bt_text, compound="center", width="50",height="20",borderwidth="0")
b.grid(row=2, column=0)

root.mainloop()

I want to give bt_text a default value and then change it everytime the button is pressed. Why doesn't it work?

mn_wy
  • 127
  • 6

1 Answers1

1

You could do it like this:

from tkinter import *

root = Tk()

def switcher():
    print(bt_text.get())
    if bt_text.get() == "A":
        bt_text.set("B")
    else:
        bt_text.set("A")

bt_text = StringVar()
b = Button(root, justify=LEFT, command=switcher)
photo1 = PhotoImage(file="background.gif")
b.config(image=photo1, textvariable=bt_text, compound="center",
         width="50", height="20", borderwidth="0")

#set the text of your button
bt_text.set('A')

b.grid(row=2, column=0)

root.mainloop()
omn_1
  • 345
  • 2
  • 14