问题描述:

Here is my code:

from tkinter import *

def command(d):

print(d)

a = Tk()

b = []

for c in range(0, 5):

b.append(Button(a, text=c, command=lambda: command(c)))

b[c].pack()

a.mainloop()

When running the script, the buttons all print 4, whereas I want them to print the number shown on them. How can you do this?

I am using Python 3.4

网友答案:

At first glance, there are a couple of things wrong here. First of all, your for loop needs to be indented four spaces like this:

for c in range(0, 5):
    b.append(Button(a, text=c, command=lambda: command(c)))
    b[c].pack()

If you don't do that, then the value of c will be 4 for the rest of the script because that is the value of c for the last iteration of range(0, 5).

The reason that your buttons are always printing 4 is because the variable c is evaluated when the callback is called, not when you assign the callback to the button. A simple way to avoid this problem is to initialize the lambda function with the current value of c using a dummy variable (we'll call it j) like this: lambda j=c: command(j). Putting this together, you should have something like

from tkinter import *    

def command(d):
   print(d)

a = Tk()
b = []

for c in range(0, 5):
    x = Button(a, text=c, command=lambda j=c: command(j)))
    x.pack()
    b.append(x)

a.mainloop()

I changed the way you packed the button because I think it's far more readable, but the end result should be the same.

相关阅读:
Top