这个问题在这里已有答案:
class Calc:
def __init__(self):
ls = ("1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "+", "/", "x", "=", "a", ".")
column = 5
row = 5
count = 2
for x in ls:
bt=Button(root, text=x, command="")
for y in x:
bt.grid(row=(row), column=(column))
column = column + 1
count = count + 1
if count> row:
column = column-4
row = row +4
cal=Calc()
以上是我的代码。我的问题是如何调用一个函数,以便按下按钮,例如按钮1,将1打印到控制台。似乎只能打印1,16个按钮的整个列表,或者我可以打印列表中最后一个位置“。”。我不能打印1或2或3等?
您可以使用lambda
为参数分配函数。
如果你在lambda
中使用for
,你必须在char=item
中使用lambda
command=lambda char=item:self.on_press(char)
因为当你使用lambda:self.on_press(item)
时它会使用item
的引用,而不是来自item
的值。当你按下按钮时它会从item
获得价值但是在for
循环之后你从列表中得到最后一个值并且所有按钮都获得相同的值。
完整代码
import tkinter as tk
class Calc:
def __init__(self, master):
ls = (
("1", "2", "3"),
("4", "5", "6"),
("7", "8", "9"),
("-", "+", "/"),
("x", "=", "a"),
(".")
)
for r, row in enumerate(ls):
for c, item in enumerate(row):
bt = tk.Button(master, text=item, command=lambda char=item:self.on_press(char))
bt.grid(row=r, column=c)
def on_press(self, char):
print(char)
# --- main ---
root = tk.Tk()
cal = Calc(root)
root.mainloop()