[英]Obtain values from tkinter OptionMenu
1 我从OptionMenu 中选择了值
2 点击按钮
但是回调 function 会parse
OptionMenu 的打印默认值。 我做错了什么?
我的代码
from tkinter import *
from functools import partial
def parse(shop, city):
print(f"Parse {city} {shop}") # prints "all shops" but i expected "magnit" because i chosed it
master = Tk()
variable_shop = StringVar(master)
variable_shop.set("all shops") # default value
w = OptionMenu(master, variable_shop, "all shops", "5ka", "magnit", "three").pack()
variable_city = StringVar(master)
variable_city.set("all cities") # default value
w2 = OptionMenu(master, variable_city, "all cities", "Moscow", "Saint Petersburg").pack()
callback = partial(parse, variable_shop.get(), variable_city.get())
b1 = Button(text="Run with values from OptionMenu", command=callback).pack()
mainloop()
您的回调行在程序启动时运行,因此它会在启动时保存值。 当用户单击按钮时,您需要将那些 get() 调用移动到稍后运行的某个地方。 将它们放入解析 function 是有道理的,并且也消除了对部分的需要。
from tkinter import *
def parse():
city = variable_city.get()
shop = variable_shop.get()
print(f"Parse {city} {shop}")
master = Tk()
variable_shop = StringVar(master)
variable_shop.set("all shops") # default value
OptionMenu(master, variable_shop, "all shops", "5ka", "magnit", "three").pack()
variable_city = StringVar(master)
variable_city.set("all cities") # default value
OptionMenu(master, variable_city, "all cities", "Moscow", "Saint Petersburg").pack()
Button(text="Run with values from OptionMenu", command=parse).pack()
mainloop()
考虑这行代码:
callback = partial(parse, variable_shop.get(), variable_city.get())
它在功能上与此相同:
shop = variable_shop.get()
city = variable_city.get()
callback = partial(parse, shop, city)
换句话说,您在创建get
方法大约一毫秒后调用它,而不是等到用户单击按钮。
您根本不需要使用partial
。 只需让回调调用常规 function,并让 function 检索值。 这将使代码更容易编写、更容易理解和更容易调试。
def parse():
shop = variable_shop.get()
city = variable_city.get()
print(f"Parse {city} {shop}")
...
b1 = Button(text="Run with values from OptionMenu", command=parse)
b1.pack()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.