作者MaJaeYun (Bonjwa)
看板Python
標題[問題] tkinter.entryconfig無法使用迴圈輸入
時間Wed Dec 8 13:08:07 2021
想要做的功能是在tkinter上面, 使用menu選單做切換
呼叫update_output後, 把一個StringVar字串更改內容
問題發生在寫entryconfigure時, 迴圈工作跟預期的不一樣
輸出給更新字串的func時,只會出現最後一個
temp_var = tk.StringVar()
test_list = [
'Test1',
'Test2',
'Test3']
for i
in range(
0,
len(test_list)):
#顯示選單正常顯示沒問題
tkmenu.add_command(label = test_list[i])
#綁定功能時永遠都是輸出最後一個'Test3'
tkmenu.entryconfigure(i,
command =
lambda: update_output(test_list[i]))
def update_output(
self,
str_var):
print(
"input var:" + str_var)
temp_var.set(str_var)
print(
"output var:" + temp_var.get())
return template_var
比對input var跟output var之後
確定輸入的時候就是'Test 3', 不管按哪一個選項都一樣
但不知道為什麼,如果如下列所示不用迴圈,直接手動輸入,完全可以正常運作
點到對的目錄選項,就會吐回來對應的字串
tkmenu.entryconfigure(
0,
command =
lambda: update_output(
'Test1'))
tkmenu.entryconfigure(
1,
command =
lambda: update_output(
'Test2'))
tkmenu.entryconfigure(
2,
command =
lambda: update_output(
'Test3'))
只能猜測是entryconfigure不能包在迴圈裡?
因為看起來不像是製作選項時的時間問題,用一個一個輸入的方式是完全正常的
是我寫錯, 或是有甚麼方法可以處理多筆目錄選項的狀況呢?
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 223.136.251.47 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1638940089.A.227.html
※ 編輯: MaJaeYun (223.136.251.47 臺灣), 12/08/2021 13:19:16
推 lycantrope: update_output是classmethod嗎?template_var沒定義 12/08 14:46
推 s0914714: command = lambda i=i: update_output(test_list[i]) 12/08 15:04
推 lycantrope: 原來是lambda scope問題i要從lambda 左側傳入 12/08 15:18
→ lycantrope: 但理論上應該可以從global傳入嗎(?) 不太懂 12/08 15:24
推 lycantrope: lambda陷阱 12/08 15:28
推 lycantrope: lambda沒在冒號左側定義會在`呼叫`時從global傳入 12/08 15:42
推 s0914714: 可以從global傳入沒問題 看執行時global變數變成啥而以 12/08 15:43
推 lycantrope: 嗯 例如 del i 就會導致i沒定義 呼叫就會失敗 12/08 15:48
→ MaJaeYun: 解決了 非常感謝兩位大大的協助~ 12/09 16:55