python tkinter按钮如何使用命令调用函数[重复]

问题描述 投票:-1回答:1

这个问题在这里已有答案:

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等?

python loops for-loop button tkinter
1个回答
1
投票

您可以使用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()
© www.soinside.com 2019 - 2024. All rights reserved.