如何将标签网格修改为按钮

时间:2015-12-15 17:09:37

标签: python tkinter

它被写成电话拨号,我需要将每个号码分成按钮,然后打印已点击的号码。

from tkinter import Tk, Label, RAISED
root = Tk()
labels = [['1', '2', '3'],
          ['4', '5', '6'],
          ['7', '8', '9'],
          ['*', '0', '#']]
for r in range(4):
    for c in range(3):
        #create label for row r and column c
        label = Label(root,
                      relief=RAISED,
                      padx=15,
                      text=labels[r][c])
        #place label in row r and column c
        label.grid(row=r, column=c)
root.mainloop()

1 个答案:

答案 0 :(得分:1)

使用Button(... , command=lambda x=some_value: some_function(x) )

from tkinter import Tk, Label, RAISED

labels = [['1', '2', '3'],
          ['4', '5', '6'],
          ['7', '8', '9'],
          ['*', '0', '#']]


def my_function(text):
    print(text)


root = Tk()

for r in range(4):
    for c in range(3):
        #create button for row r and column c
        Button(root,
              relief=RAISED,
              padx=15,
              command=lambda x=labels[r][c]: my_function(x),
              text=labels[r][c]).grid(row=r, column=c)

root.mainloop()