2015-08-03 42 views
1

我正在嘗試將代碼實現到我的程序中,以便在用戶將鼠標光標懸停在其上時更新按鈕顏色。該程序識別懸停,但返回錯誤。將顏色綁定到Tkinter中的按鈕導致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" 

我已經谷歌搜索如何做懸停時發生的顏色變化,並找到以下代碼。雖然由於某種原因,它不適合我。我究竟做錯了什麼?

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

這是我最初定義的結果的代碼,這些代碼來自achievementButton。

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

回答

2

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的臉部顏色。

+0

因此,沒有實際的方法來保持使用ttk的Windows 7/8/10的漂亮的按鈕設計?這有點令人失望,但你確實幫了我。謝謝。 – orias