[問題] tkinter.entryconfig無法使用迴圈輸入

看板Python作者 (Bonjwa)時間2年前 (2021/12/08 13:08), 2年前編輯推噓10(1002)
留言12則, 4人參與, 2年前最新討論串1/1
想要做的功能是在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

12/08 14:46, 2年前 , 1F
update_output是classmethod嗎?template_var沒定義
12/08 14:46, 1F

12/08 15:01, 2年前 , 2F

12/08 15:04, 2年前 , 3F
command = lambda i=i: update_output(test_list[i])
12/08 15:04, 3F

12/08 15:18, 2年前 , 4F
原來是lambda scope問題i要從lambda 左側傳入
12/08 15:18, 4F

12/08 15:23, 2年前 , 5F

12/08 15:24, 2年前 , 6F
但理論上應該可以從global傳入嗎(?) 不太懂
12/08 15:24, 6F

12/08 15:28, 2年前 , 7F
lambda陷阱
12/08 15:28, 7F

12/08 15:35, 2年前 , 8F

12/08 15:42, 2年前 , 9F
lambda沒在冒號左側定義會在`呼叫`時從global傳入
12/08 15:42, 9F

12/08 15:43, 2年前 , 10F
可以從global傳入沒問題 看執行時global變數變成啥而以
12/08 15:43, 10F

12/08 15:48, 2年前 , 11F
嗯 例如 del i 就會導致i沒定義 呼叫就會失敗
12/08 15:48, 11F

12/09 16:55, 2年前 , 12F
解決了 非常感謝兩位大大的協助~
12/09 16:55, 12F
文章代碼(AID): #1Xi3sv8d (Python)