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

时间:2018-12-05 00:31:32

标签: python tkinter fonts label attributeerror

我正在尝试创建一个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'

1 个答案:

答案 0 :(得分:0)

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

此外,创建窗口小部件时self.fgfg属性不同(例如:Label(..., fg="blue")。如果要获取窗口小部件属性的值,则应使用self.cget('fg')或使用快捷键self['fg']。如果要在类本身中进行设置,则应使用self.configure(fg="purple")