使用for迴圈建立10個button,每一個button功能為印出自己的編號

442 views
Skip to first unread message

Chen IShung

unread,
Dec 20, 2017, 4:37:52 AM12/20/17
to python.tw
各位大大好,如題,寫完的code每一個button只能印出迴圈最後一個數字,但是button編號顯示又正常,還請大大指教。

from tkinter import *
from tkinter import ttk

def show_btn(pathname, value):
print (pathname)
print (value)
pathname.insert(END, value)

def main_gui():
win = Tk()
en_1=ttk.Entry(win)
en_1.pack()
for i in range(1,11):
btn_i=ttk.Button(win, text=i, command=lambda:show_btn(en_1, i))
btn_i.pack()
win.mainloop()

main_gui()

Apua

unread,
Dec 21, 2017, 10:44:14 AM12/21/17
to pyth...@googlegroups.com
The variable `i` in the statement `lambda: show_btn(en_1, i)` is not
local variable thus they are all the same `i` instance and value.

One way to fix is using `closure`_, where every `i` is bound to
different scopes and so that different instances.

.. _closure: https://gist.github.com/apua/e43f007fbc9813ae97f7831ed25bb62b


Apua
> --
> 這是 Google 網上論壇針對「python.tw」群組發送的訂閱通知郵件。
> 如要取消訂閱這個群組並停止接收來自這個群組的郵件,請傳送電子郵件到 pythontw+u...@googlegroups.com
> 如要在這個群組張貼留言,請傳送電子郵件到 pyth...@googlegroups.com
> 請前往以下網址造訪這個群組:https://groups.google.com/group/pythontw
> 如需更多選項,請前往:https://groups.google.com/d/optout
Reply all
Reply to author
Forward
0 new messages