【问题标题】:How to change background in button with command, inside a class python tkinter OOP?如何在类 python tkinter OOP 中使用命令更改按钮的背景?
【发布时间】:2020-05-02 18:40:40
【问题描述】:

欢迎 我想让棋盘像象棋一样。单击此按钮后,应使用“命令”方法更改您的背景。我尝试输入我的代码 StringVar()、.config、全局变量和 lambda。如果有解决此问题的链接,我会很高兴。 (这是我在这个网站上的第一个问题,对一切感到抱歉)

from tkinter import *

class App():
    """docstring for App"""
    root=Tk(className="application 4")
    x, y = 0, 0
    tab = []

    def __init__(self, x, y):
        App.x = x
        App.y = y
        App.root.geometry("800x600")
        App.root.resizable(height = FALSE, width = FALSE)
        for i in range(App.x):
            for j in range(App.y):
                App.tab.append(Button(App.root, width=1, bg="white", command=lambda: self.changeBG(self)).grid(row=i, column=j))
        App.root.mainloop()


    def changeBG(self, btn):
        self.config(bg = "red")


application = App(10, 10)

错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\S\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "C:\Users\S\Desktop\Spanish number project\clicked.py", line 16, in <lambda>
    App.tab.append(Button(App.root, width=1, bg="white", command=lambda: self.changeBG(self)).grid(row=i, column=j))
  File "C:\Users\S\Desktop\Spanish number project\clicked.py", line 21, in changeBG
    self.config(bg = "red")
AttributeError: 'App' object has no attribute 'config'
[Finished in 6.4s]

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    虽然我一直想学习,但我之前从未使用过tkinter 模块。

    所以这是调试代码的尝试。免责声明:此代码按预期运行。我不知道它是否遵循使用tkinter 创建应用程序的约定。我使用问题中的示例代码作为指导。

    问题的线索在异常中:changeBG self.config(bg = "red") AttributeError: 'App' object has no attribute 'config'

    我的第一个猜测是按钮必须具有您要修改的属性,而不是 self 命名的 App 类实例。

    我创建了一个矩阵(二维列表或“列表列表”),其中可以存储按钮。

    请注意,您的代码会创建一个Button 实例,然后在按钮上调用grid 方法,而无需将按钮实例存储在名称中。该grid 方法的返回是None。原始代码中的self.tabNones 的列表。在我的代码中,我在按钮实例化后调用了grid

    我使用这个答案来弄清楚如何将参数传递给命令回调,因为没有隐式传递参数:

    https://stackoverflow.com/a/35780253/1913726

    rowcol 的值在 lambda 中捕获。当单击按钮时,实例方法changeBG 会在 lambda 中调用,并使用适当的参数,从矩阵中检索按钮,并更新背景颜色。

    我在你的课堂上做了一些修改。

    from tkinter import *
    
    
    class App:
    
        root = Tk(className="application 4")
        root.geometry("800x600")
        root.resizable(height=FALSE, width=FALSE)
    
        def __init__(self, x, y):
            # create a matrix for the buttons
            self.tab = [[None] * y for _ in range(x)]
            for row in range(x):
                for col in range(y):
                    button = Button(
                        self.root,
                        width=1,
                        bg="white",
                        # use keyword arguments to pass values into instance method
                        command=lambda row=row, col=col: self.changeBG(row, col),
                    )
                    # place the button on a grid after instantiation
                    # The return of `grid` is None
                    button.grid(row=row, column=col)
                    # assign the value in the matrix to the button
                    self.tab[row][col] = button
            self.root.mainloop()
    
        def changeBG(self, row, col):
            # the button has the attribute "config"
            button = self.tab[row][col]  # get button from matrix
            button.config(bg="red")
            print(f"You clicked button '{button}' at row {row} and col {col}")
    
    
    application = App(10, 10)
    

    【讨论】:

    • 不客气。我从帮助你回答这个问题中学到了很多。
    猜你喜欢
    • 2020-10-09
    • 1970-01-01
    • 2010-09-09
    • 2016-09-11
    • 1970-01-01
    • 2021-03-22
    • 2019-10-06
    • 1970-01-01
    • 2023-04-10
    相关资源
    最近更新 更多