John J. Johnson
John J. Johnson

Reputation: 65

tkinter: Adjust Label text based on changed OptionMenu

In a canvas there is a button 'new entry' that starts a Toplevel. It has a submit Button, a cancel Button, an OptionMenu, and a Label. The objective is that the selected value from the OptionMenu changes the Label text. I didn't add the code for the canvas.

def Test(value):
    p = value
    print(p) # a test
    E2.config(text=str(p))

def Vullen_Toplevel_Aankoop_EUR(i):
    top = Toplevel()
    top.geometry("%dx%d%+d%+d" % (600, 800, 250, 125))

    BSubmit = Button(top, text="Submit", fg='green')
    BSubmit.grid(row=1, column=0, sticky="ew", columnspan=1, padx=20)

    BCancel = Button(top, text="Cancel", fg='red', command=top.destroy)
    BCancel.grid(row=10, column=0, sticky="ew", columnspan=1, padx=20)

    p = None
    E2 = None

    E1_opt = ["A","B","C"]
    E1_var = StringVar(top)
    E1_var.set(E1_opt[0])
    W1 = OptionMenu(top, E1_var, *E1_opt, command=Test)
    W1.grid(row=2, column=1, sticky="ew")

    E2 = Label(top, text='test')
    E2.grid(row=4, column=2, sticky="ew")

The default value of variable p is 'empty'. The OptionMenu triggers command=Test which prints the new value for p on the console. So far so good.

I tried to update Label E2 with: E2.config(test=str(p)). Unfortunately the error message:

NameError: name 'E2' is not defined

Although not added to the code here, I tried the following:

I am kind of out of ideas. Would you have insights to share? Thanks.

Upvotes: 0

Views: 319

Answers (1)

furas
furas

Reputation: 142641

Create global variable outside all functions

E2 = None

Use global E2 to inform function than you want to assign value to global/external variable E2. Without global it will create local variable E2 and it doesn't assign to global one.

def Vullen_Toplevel_Aankoop_EUR(i):
    global E2 # you need it because you use `E2 = ...`

    E2 = Label(top, text='test')

Full

# create global variable
E2 = None

def Test(value):
    #global E2 # you don't need it because you don't use `E2 = ...`

    E2.config(text=value)

def Vullen_Toplevel_Aankoop_EUR(i):
    global E2 # you need it because you use `E2 = ...`

    E2 = Label(top, text='test')

# you can create also after functions
#E2 = None

BTW: shorter

 top.geometry("600x800+250+125")

Upvotes: 0

Related Questions