[英]How to change the value of an option menu after user clicks?
I'm playing around with option menu.我在玩选项菜单。 I have a list of countries called options.
我有一个称为选项的国家/地区列表。 The option menu is set to the first index of options.
选项菜单设置为选项的第一个索引。 How can I update the value if a user clicks on a different country?
如果用户单击不同的国家/地区,我如何更新该值? Basically the function doesn't work even though I click on the 2nd (options[1]) country in the option menu.
即使我单击选项菜单中的第二个(选项 [1])国家,基本上该功能也不起作用。
def first_country():
from_country = start_clicked.get()
if from_country == options[1]:
my_pic = Image.open("usa_flag.png")
resized = my_pic.resize((200, 100), Image.ANTIALIAS)
new_pic = ImageTk.PhotoImage(resized)
flag_label = Label(root, image=new_pic)
flag_label = Label(root, text="function works")
flag_label.grid(row=3, column=0)
start_clicked = StringVar()
start_clicked.set(options[0])
dropdown = OptionMenu(root, start_clicked, *options, command=first_country())
In Python, whenever you add ()
to the end of a function, it invokes it.在 Python 中,每当您在函数末尾添加
()
,它都会调用它。 (aside from declaration) (声明除外)
This being the case, it is usually so that when you are to pass a function to something, you need only pass a reference to the function在这种情况下,通常是这样,当您将函数传递给某物时,您只需要传递对该函数的引用
Effectively, just remove the ()
实际上,只需删除
()
dropdown = OptionMenu(root, start_clicked, *options, command=first_country)
Comment from acw1668 explained it well:来自 acw1668 的评论很好地解释了它:
command=first_country() should be command=first_country instead.
command=first_country() 应该改为 command=first_country。 The former one will execute the function immediately and assign None to command .
前一个将立即执行该函数并将 None 分配给 command 。
command=first_country()
should be command=first_country
instead. command=first_country()
应该改为command=first_country
。 The former one will execute the function immediately and assign None
(result of the function) to command
option.前一个将立即执行函数并将
None
(函数的结果)分配给command
选项。
Also the callback for command
option of OptionMenu
expects an argument which is the selected item:此外,
OptionMenu
command
选项的OptionMenu
需要一个参数,即所选项目:
def first_country(from_country):
if from_country == options[1]:
my_pic = Image.open("usa_flag.png")
resized = my_pic.resize((200, 100), Image.ANTIALIAS)
new_pic = ImageTk.PhotoImage(resized)
# better create the label once and update its image here
flag_label.config(image=new_pic)
flag_label.photo = new_pic # save a reference of the image
...
dropdown = OptionMenu(root, start_clicked, *options, command=first_country)
...
# create the label for the flag image
flag_label = Label(root)
flag_label.grid(row=3, column=0)
...
Note that I have created the label for the flag image once and update its image inside the function instead.请注意,我已经为标志图像创建了一次标签,并在函数内部更新了它的图像。 Also you need to save the reference of the image if it is created inside a function, otherwise it will be garbage collected.
如果在函数内部创建图像,还需要保存图像的引用,否则将被垃圾收集。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.