我在玩選項選單。我有一個稱為選項的國家/地區串列。選項選單設定為選項的第一個索引。如果用戶單擊不同的國家/地區,我如何更新該值?即使我單擊選項選單中的第二個(選項 [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())
uj5u.com熱心網友回復:
在 Python 中,每當您添加()到函式的末尾時,它都會呼叫它。(宣告除外)
在這種情況下,通常是這樣,當您將函式傳遞給某物時,您只需要傳遞對該函式的參考
有效地,只需洗掉 ()
dropdown = OptionMenu(root, start_clicked, *options, command=first_country)
來自 acw1668 的評論很好地解釋了它:
command=first_country() 應該改為 command=first_country。前一個將立即執行該函式并將 None 分配給 command。
uj5u.com熱心網友回復:
command=first_country()應該是command=first_country。前一個將立即執行函式并將None(函式的結果)分配給command選項。
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)
...
請注意,我已經為標志影像創建了一次標簽,并在函式內部更新了它的影像。如果在函式內部創建影像,還需要保存影像的參考,否則將被垃圾收集。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/357568.html
上一篇:在Python中繪制正方形
下一篇:對齊按鈕中的文本
