You have two problems:
First: mainloop()
starts window so your pri()
is executed before you see window - so before you could selecte anything. I add pri
to button so you can also see how it works after selecting option.
Second: all variables create outside functions/classes are global and they don't need keyword global
. You have to use global
inside function to inform function that when you will assign value using =
then you what to use external/global variable instead of creating local one.
In code I have global variable normal_var
and I use global normal_var
inside grab_and_assign
to inform function to assign value to global variable and not to create local variable in line
normal_var = var.get()
I don't have to use global
inside pri()
because I only get value from variable nromal_var
and don't use =
to assign new value
I don't have to use global
to assign new value for:
var
because it uses set()
instead of =
.
label_selected["text"]
because it assign value to key in dictionary.
But I would have to use global
for label_selected
if I would like to assign new Label
inside function - ie. label_selected = tk.Label(..)
import tkinter as tk
# --- functions ---
def grab_and_assign(event):
global normal_var
normal_var = var.get()
label_selected["text"] = var.get()
def pri():
print('normal_var:', normal_var)
print('var.get():', var.get())
print('---')
# --- main ---
# global variable
normal_var = "- empty -"
root = tk.Tk()
root.title("Drop-down boxes for option selections.")
# it is global variable
var = tk.StringVar(root)
var.set("drop down menu button")
drop_menu = tk.OptionMenu(root, var, "one", "two", "three", "four", "meerkat", "12345", "6789", command=grab_and_assign)
drop_menu.grid(row=0, column=0)
label_left = tk.Label(root, text="chosen variable = ")
label_left.grid(row=1, column=0)
# create it only once
label_selected = tk.Label(root, text="?")
label_selected.grid(row=1, column=1)
# execute `pri` after button press
b = tk.Button(root, text='PRI', command=pri)
b.grid(row=2, column=0)
# execute `pri` before window starts
pri()
root.mainloop()
BTW: Label
has textvariable=
and you can assign var
which you use in OptionMenu
and then it will automatically display selected value
import tkinter as tk
# --- main ---
root = tk.Tk()
var = tk.StringVar(root)
var.set("drop down menu button")
label_selected = tk.Label(root, textvariable=var)
label_selected.pack()
drop_menu = tk.OptionMenu(root, var, "one", "two", "three", "four", "meerkat", "12345", "6789")
drop_menu.pack()
root.mainloop()