尝试使用绑定命令更改 tkinter 标签颜色时出现 AttributeError

AttributeError when trying to change tkinter label color with bound command

我正在尝试创建一个 tkinter 标签,该标签在单击时会改变颜色以表明它已被访问过。我不断收到属性错误,指出 Show_Label 没有属性 'fg'。请帮忙!这是正在使用的代码。

class Sheet_Label(Label):
    def __init__(self,master,text):

        Label.__init__(self,master,text=text,cursor="hand2",font="Times 16 underline",fg="blue")
        def button_click(event):
            if self.fg =="blue":
                self.fg = "purple"
            else:
                self.fg = "purple"
            location = os.getcwd()
            file = webbrowser.open_new(location + '\' + "hello.txt")
        self.bind("<Button-1>",func=button_click)

def sheets_view():
    sheets_window = Toplevel(window)
    hello = modules.Sheet_Label(master=sheets_window,text="Hello")
    hello.pack(padx=10,pady=10)
    sheets_window.title("Production Sheets")
    sheets_window.focus()
    x = (screen_width/2) - (500/2)
    y = (screen_height/2) - (500/2)
    sheets_window.geometry("%dx%d+%d+%d" % (500,500,x,y))
    sheets_window.resizable(0,0)

错误信息如下:

Traceback (most recent call last):
  File "C:\Users\napaf\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
  File "inventory.py", line 311, in sheets_view

    hello = modules.Sheet_Label(master=sheets_window,text="Hello")
  File "C:\Users\napaf\Documents\Programming\adco_project\modules.py", line 24, in __init__
    self.action = action
NameError: name 'action' is not defined
PS C:\Users\napaf\Documents\Programming\adco_project> python inventory.pyException in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\napaf\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
  File "C:\Users\napaf\Documents\Programming\adco_project\modules.py", line 27, in button_click
    if self.fg =="blue":
AttributeError: 'Sheet_Label' object has no attribute 'fg'

在调用 button_click 之前,您不会初始化 self.fg,但此时为时已晚,因为您试图在设置它之前引用 self.fg

此外,self.fg 与创建小部件时的 fg 属性不同(例如:Label(..., fg="blue")。如果您想获取小部件属性的值,您应该使用 self.cget('fg') 或使用快捷方式 self['fg']。如果你想从 class 本身中设置它,你应该使用 self.configure(fg="purple")