我目前正在尝试创建一个拨号盘,用于打印在shell中按下的按钮。这是我到目前为止的代码:
from tkinter import Tk, Button, RAISED
root = Tk()
buttons = [['1','2','3'],
['4','5','6'],
['7','8','9'],
['*','0','#']]
def clicked():
print(Button)
for r in range(4):
for c in range(3):
button = Button(root,
relief = RAISED,
padx = 10,
text = buttons[r][c],
command = clicked)
button.grid(row = r, column = c)
root.mainloop()
***OUTPUT***
<class 'tkinter.Button'>
执行时,拨号盘显示正确,但按下按钮时,控制台中不会打印该号码,而是打印上述内容。很抱歉,如果这是我的一个简单错误,但我正在尝试自学Python,而且我还是比较新的。
非常感谢任何帮助。
答案 0 :(得分:2)
你基本上传递了Tk按钮,但你需要传递按钮值,为了一个安全而好的方式只需使用部分
from Tkinter import Tk, Button, RAISED
from functools import partial
root = Tk()
buttons = [['1','2','3'],
['4','5','6'],
['7','8','9'],
['*','0','#']]
def buttonClicked(buttonVal):
print(buttonVal)
for r in range(4):
for c in range(3):
button = Button(root,
relief = RAISED,
padx = 10,
text = buttons[r][c],
command = partial(buttonClicked, buttons[r][c]))
button.grid(row = r, column = c)
root.mainloop()