开发者

Python Tk Multiple Buttons Creation Problem

开发者 https://www.devze.com 2023-03-28 04:45 出处:网络
I\'m creating ten buttons and the button texts are labelled 1 to 10. The following code creates 10 buttons and labels correctly. But it\'s printing 9as the output for all the buttons. What I expect it

I'm creating ten buttons and the button texts are labelled 1 to 10. The following code creates 10 buttons and labels correctly. But it's printing 9 as the output for all the buttons. What I expect it to do is to print the corresponding number of the Button to screen, So for Example if the user presses Button 2 then it should print 2.

def create():
for i in range (1,10):
    lst.insert(i,Button(text=i,command=lambda: prnt(i)).pack())

(Note: 'prnt(i)' is a function that simply prints the value i has. 'lst' is a list that stores the created buttons.)

From the output I can say that the program is using the latest i value as the argument for the function when user presses a button, So how would I solve this with开发者_如何转开发out having to write 10 lines of code for each buttons.


Try this (note the named argument to the lambda):

def create():
    for i in range (1,10):
        lst.insert(i,Button(text=i,command=lambda i=i : prnt(i)).pack())

This passes the value of i to the lambda as a local variable. Without this, you are using a reference to the original variable which will, of course, always resolve to whatever is stored in the original variable.

0

精彩评论

暂无评论...
验证码 换一张
取 消