Python Tkinter,用循环设置按钮回调函数 [英] Python Tkinter, setting up button callback functions with a loop
问题描述
我正在编写一个显示按钮网格的程序,当按下按钮时,我希望它打印出网格中按钮的位置(行列")到控制台.这是我所拥有的
I'm writing a program that displays a grid of buttons, when a button is pressed I want it to print the location of the button in the grid ("row column") out to the console. Here is what I have
import Tkinter as tk
class board(tk.Tk):
def __init__(self, parent=None):
tk.Tk.__init__(self,parent)
self.rows = 5
self.columns = 5
self.init_board()
def init_board(self):
for i in range(self.rows):
for j in range(self.columns):
cmd = lambda: self.button_callback(i,j)
b = tk.Button(self, text=str(" "), command=cmd)
b.grid(row=i, column=j)
def button_callback(self, row, col):
print(str(row) + " " + str(col))
if __name__ == '__main__':
board().mainloop()
问题是,当我单击任何按钮时,我会打印出4 4",这是循环中实例化的最后一个按钮的位置.我不知道为什么会发生这种情况,请帮助!
the problem is that when I click on any of the buttons I get "4 4" printed out which is the location of the last button instantiated in the loop. I don't know why this is happening, please help!
推荐答案
在使用lambda
创建的函数中,i
,j
指的是init_board
函数中的变量,在 for
循环结束后设置为 4、4.
In the function created using lambda
, i
, j
refers to the varaible in the init_board
function, which are set to 4, 4 after the for
loop ends.
您可以使用默认参数解决此问题.
You can workaround this using default argument.
替换以下行:
cmd = lambda: self.button_callback(i,j)
与:
cmd = lambda i=i, j=j: self.button_callback(i,j)
这篇关于Python Tkinter,用循环设置按钮回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!