[英]Saving output after choosing option menu (python - Tkinter)
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?在用户点击 OK 按钮并且 window 在 Tkinter 中关闭之后,我试图保存用户的选择 [Red, Green-red, Green-blue, blue] ......到目前为止,我已经使用了一些东西我在网上找到了,但我无法推断出一种“简单”的方法?
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.我将它保存在频道下,但它在 function 之外不可用。 hmm唔
Use global
to assign value to global variable使用global
为全局变量赋值
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:使用return channel
没有意义,因为 function 是通过按钮执行的,它不能返回值并分配给其他值。
BTW: If you want save only channel
then maybe do it inside function ok()
顺便说一句:如果你只想保存channel
,那么可以在 function ok()
BTW: You should use [0]
in var.set(OPTIONS[0])
to set only first element as default/initial value.顺便说一句:您应该在var.set(OPTIONS[0])
中使用[0]
仅将第一个元素设置为默认/初始值。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.