【问题标题】:AttributeError when trying to change tkinter label color with bound command尝试使用绑定命令更改 tkinter 标签颜色时出现 AttributeError
【发布时间】:2019-05-06 12:00:18
【问题描述】:

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

【问题讨论】:

  • 不应该是bg而不是fg吗?你想达到什么目的?设置backg圆形颜色?
  • 属性是fg,因为文本的前景色是我要改的属性。

标签: python tkinter fonts label attributeerror


【解决方案1】:

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

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

【讨论】:

  • 谢谢!它运行良好,对于任何想知道未来的人来说,这是我所做的更改: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("&lt;Button-1&gt;",func=button_click)
  • @BlorbieRandy:在评论中发布 python 代码毫无意义,因为所有格式都丢失了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-19
  • 2021-08-06
  • 2012-10-06
  • 2010-11-02
  • 2021-09-17
  • 1970-01-01
  • 2021-12-04
相关资源
最近更新 更多