I'm attempting to save the choice of the user [Red, Green-red, Green-blue, blue] after the user hits the okay button and the window closes in Tkinter... I've put this together so far using things I've found online but I can't deduce a "simple" way of doing this?
def select_channel():
OPTIONS = [
"Red",
"Green-red",
"Green-blue",
"Blue"
]
master = tk.Tk()
var = tk.StringVar(master)
var.set(OPTIONS) # initial value
option = tk.OptionMenu(master, var, *OPTIONS)
option.pack()
def ok():
print("value is", var.get())
channel = var.get()
master.destroy()
button = tk.Button(master, text="OK", command=ok)
button.pack()
tk.mainloop()
Any thoughts? I save it under channel but its not available outside of that function. hmm
Use global
to assign value to global variable
def ok():
global channel
print("value is", var.get())
channel = var.get()
master.destroy()
BTW: There is no sense to use return channel
because function is executed by button and it can't returned value and assign to other value.
BTW: If you want save only channel
then maybe do it inside function ok()
BTW: You should use [0]
in var.set(OPTIONS[0])
to set only first element as default/initial value.
import tkinter as tk
# --- functions ---
def select_channel():
def ok():
global channel
#print("value is", var.get())
channel = var.get()
master.destroy()
OPTIONS = [
"Red",
"Green-red",
"Green-blue",
"Blue"
]
master = tk.Tk()
var = tk.StringVar(master)
var.set(OPTIONS[0]) # initial value
option = tk.OptionMenu(master, var, *OPTIONS)
option.pack()
button = tk.Button(master, text="OK", command=ok)
button.pack()
tk.mainloop()
# --- main ---
select_channel()
print('after closing window:', channel)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.