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:
- Define E2 Label as 'empty' or as the Label just below where I defined 'p', the error is the same.
- Define E2 Label in def Test(value) but here - of course - the error is that Toplevel() top is not defined.
- Instead of command=Test I tried command=lambda: Test(top, E1_var.get()) and changed the Test method to def Test(top, value) but then the error is: TypeError: () takes 0 positional arguments but 1 was given
I am kind of out of ideas. Would you have insights to share? Thanks.
E2is local variable which exists only in one function. Define it outside all function - ie.E2 = Noneand then you will have global variable. And then you can inform functions to use this variable by usingglobal E2insideVullen_Toplevel_Aankoop_EUR(because you use=to assign value). InTestyou don't have to useglobal E2because you don't use=and it will use externalE2automatically. - furasE2 = NoneOUTSIDE FUCTIONS - and useglobal E2INSIDE FUNCTIONS. - furas