簡體   English   中英

在Tkinter中將顏色綁定到按鈕會導致TclError

[英]Binding a Color to a Button in Tkinter Results in a TclError

我目前正在嘗試在程序中實現代碼,以在用戶將鼠標指針懸停在按鈕上時更新按鈕顏色。 程序識別出懸停,但返回錯誤。

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"

我用Google搜索了懸停時如何進行顏色更改,並找到了以下代碼。 盡管出於某種原因,它對我不起作用。 我究竟做錯了什么?

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

這是我最初定義AchievementsButton的代碼。

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

ttk.Button實例沒有bgbackground屬性。 有兩種解決方案:

  • 使用具有bg屬性的普通tkinter.Button
  • 繼續使用ttk.Button,並使用樣式對象對其進行配置。 有關更多信息,請參見使用和自定義ttk樣式 例:

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()

但是,這只會更改實際按鈕后面區域的背景顏色,而不是按鈕表面。 這篇文章似乎表明無法更改ttk按鈕的外觀顏色。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM