簡體   English   中英

用戶單擊后如何更改選項菜單的值?

[英]How to change the value of an option menu after user clicks?

我在玩選項菜單。 我有一個稱為選項的國家/地區列表。 選項菜單設置為選項的第一個索引。 如果用戶單擊不同的國家/地區,我如何更新該值? 即使我單擊選項菜單中的第二個(選項 [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())  

在 Python 中,每當您在函數末尾添加() ,它都會調用它。 (聲明除外)

在這種情況下,通常是這樣,當您將函數傳遞給某物時,您只需要傳遞對該函數的引用

實際上,只需刪除()

dropdown = OptionMenu(root, start_clicked, *options, command=first_country)    

來自 acw1668 的評論很好地解釋了它:

command=first_country() 應該改為 command=first_country。 前一個將立即執行該函數並將 None 分配給 command

command=first_country()應該改為command=first_country 前一個將立即執行函數並將None (函數的結果)分配給command選項。

此外, 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)
...

請注意,我已經為標志圖像創建了一次標簽,並在函數內部更新了它的圖像。 如果在函數內部創建圖像,還需要保存圖像的引用,否則將被垃圾收集。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM