-1

I don't know what I'm doing wrong but when I create Toplevel in a function it doesn't recognize it as a global variable. When I put global or nonlocal before the creation of the toplevel widget, a message stating that there's invalid syntax is displayed.

def StartClick():
  MainMenu.withdraw
  nonlocal CHONE_1Sc = tk.Toplevel()
Thingamabobs
  • 7,274
  • 5
  • 21
  • 54
  • 2
    You obviously need to learn about namespaces in python. With this knowledge you can solve this issue and answer your two separate questions for yourself. There is tons of material for it already out there and I don't feel the need for another answer to this topic. – Thingamabobs Jun 11 '23 at 10:13
  • You need two lines: `global CHONE_1Sc` and then `CHONE_1Sc = tk.Toplevel()`. – acw1668 Jun 11 '23 at 16:04

1 Answers1

-1

To get a variable in Tkinter, you can use the get() method. The get() method takes one argument, which is the name of the variable. For example, the following code will get the value of the variable my_variable:

import tkinter as tk

root = tk.Tk()

my_variable = tk.StringVar()
my_variable.set("Hello, world!")

label = tk.Label(root, textvariable=my_variable)
label.pack()

button = tk.Button(root, text="Get value", command=lambda: print(my_variable.get()))
button.pack()

root.mainloop()

You can now implement your version of the above code this way and avoid using globals (or nonlocals)...

D.L
  • 4,339
  • 5
  • 22
  • 45
  • This still has a global variable named `my_variable`. You can have global variables without using the global keyword. Also this doesn't look anything like OP's code. – TheLizzard Jun 11 '23 at 11:41
  • seems generated by chatgpt or bard. Jusr FYI @TheLizzard – Nordine Lotfi Jun 11 '23 at 12:17
  • @NordineLotfi, yes, this is standard boiler plate. using `set()` and `get()` are the correct way to get variables into and out of tkinter... if you would like to suggest different, then please put such a suggestion forwards. – D.L Jun 11 '23 at 19:20
  • How does this answer address OP problem? – acw1668 Jun 12 '23 at 15:12