【问题标题】:Binding a Color to a Button in Tkinter Results in a TclError在 Tkinter 中将颜色绑定到按钮会导致 TclError
【发布时间】:2015-10-25 14:51:37
【问题描述】:

我目前正在尝试在我的程序中实现代码,以在用户将鼠标光标悬停在按钮上时更新按钮颜色。程序识别悬停,但返回错误。

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python34\lib\tkinter\__init__.py", line 1482, in __call__
    return self.func(*args)
  File "C:\Users\oiest\Documents\Programs\iNTMI\v1.1.3b\iNTMI.py", line 252, in <lambda>
    achievementsButton.bind("<Enter>", lambda event: achievementsButton.configure(bg = "red"))
  File "C:\Python34\lib\tkinter\__init__.py", line 1270, in configure
    return self._configure('configure', cnf, kw)
  File "C:\Python34\lib\tkinter\__init__.py", line 1261, in _configure
    self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: unknown option "-bg"

我在谷歌上搜索了如何在悬停时更改颜色并找到以下代码。虽然由于某种原因,它对我不起作用。我做错了什么?

    achievementsButton.bind("<Enter>", lambda event: achievementsButton.configure(bg = "red"))
    achievementsButton.bind("<Leave>", lambda event: achievementsButton.configure(bg = "white"))

这是我最初定义成就按钮的代码。

    achievementsButton = ttk.Button(self, text = "Achievements", command = lambda: controller.show_frame(achievements), width = "25")

【问题讨论】:

    标签: python python-3.x tkinter


    【解决方案1】:

    ttk.Button 实例没有bgbackground 属性。有两种解决方案:

    • 使用普通的tkinter.Button,它确实有一个bg属性。
    • 继续使用 ttk.Button,并使用样式对象对其进行配置。请参阅Using and customizing ttk styles 了解更多信息。示例:

     

    from Tkinter import *
    import ttk
    root = Tk()
    s = ttk.Style()
    s.configure("regular.TButton", background="red")
    s.configure("onhover.TButton", background="white")
    button = ttk.Button(root, style="regular.TButton")
    button.pack()
    button.bind("<Enter>", lambda event: button.configure(style="onhover.TButton"))
    button.bind("<Leave>", lambda event: button.configure(style="regular.TButton"))
    root.mainloop()
    

    但是,这只会改变实际按钮后面区域的背景颜色,而不是按钮的正面。 This 帖子似乎表明无法更改 ttk Button 的面颜色。

    【讨论】:

    • 所以没有实际的方法来使用 ttk 来保持 Windows 7/8/10 的漂亮按钮设计?这有点令人失望,但你确实帮助了我。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2020-04-21
    • 2018-06-10
    • 1970-01-01
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    • 2014-02-22
    相关资源
    最近更新 更多