1我从OptionMenu选择值。
2点击按钮
但是回调函数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()发布于 2020-12-01 21:17:39
您的回调行在程序启动时运行,因此它在引导时保存值。当用户单击按钮时,您需要将那些get()调用移动到稍后运行的某个地方。将它们放入解析函数中是有意义的,同时也消除了对分部的需要。
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()发布于 2020-12-01 21:17:56
考虑这一行代码:
callback = partial(parse, variable_shop.get(), variable_city.get())它在功能上与此相同:
shop = variable_shop.get()
city = variable_city.get()
callback = partial(parse, shop, city)换句话说,您在创建get方法之后调用它大约一毫秒,而不是等到用户单击该按钮后再调用它。
您根本不需要使用partial。只需让回调调用一个常规函数,并让该函数检索值。这将使代码更易于编写、更易于理解和更易于调试。
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()https://stackoverflow.com/questions/65098586
复制相似问题