鼠标悬停时无法更改tkinter画布背景颜色吗?

时间:2018-10-12 14:16:44

标签: python python-3.x tkinter tkinter-canvas

每当鼠标悬停在画布上时,我都希望更改其背景颜色。有此代码。最小示例:

import tkinter as tk

class HoverCanvas(tk.Canvas):
    def __init__(self, master, activebackground, **kw):
        tk.Frame.__init__(self,master=master,**kw)
        self.defaultBackground = self["background"]
        self.activebackground = activebackground
        self.bind("<Enter>", self.on_enter)
        self.bind("<Leave>", self.on_leave)

    def on_enter(self, e):
        self.config(background=self.activebackground)

    def on_leave(self, e):
        self.config(background=self.defaultBackground)



root = tk.Tk()
root.geometry("1280x720")

canvas = HoverCanvas(root, 'red', bg='#212121', width=1280, height=720)
#canvas = tk.Canvas(root, bg='#212121', width=1280, height=720)
canvas.create_text(110, 15, fill="#304ffe", activefill='#6a1b9a', font="Times   14 bold", text="Soccer Data Scraper v1.0")
canvas.grid(row=0, column=0)

root.mainloop()

如果鼠标为空,则画布的颜色将变为红色(请参见注释行)。 但是,如果我尝试在画布上添加文本或任何其他小部件,则该程序将停止工作并抛出一个神秘错误。

Traceback (most recent call last):
  File "canvasbg.py", line 24, in <module>
canvas.create_text(110, 15, fill="#304ffe", activefill='#6a1b9a', font="Times  14 bold", text="Soccer Data Scraper v1.0")
  File "C:\Program Files (x86)\Python37-32\lib\tkinter\__init__.py", line 2501, in create_text
return self._create('text', args, kw)
  File "C:\Program Files (x86)\Python37-32\lib\tkinter\__init__.py", line 2477, in _create
*(args + self._options(cnf, kw))))
_tkinter.TclError: bad option "create": must be cget or configure

这是什么错误?有没有办法改变光标悬停时画布的背景颜色,同时还包含其他小部件/文本?

任何帮助表示赞赏。谢谢

1 个答案:

答案 0 :(得分:2)

您的课程继承自tk.Canvas

class HoverCanvas(tk.Canvas):

但是您调用了__init__的{​​{1}}方法

tk.Frame

您应该改为调用tk.Frame.__init__(self,master=master,**kw) 的{​​{1}}方法。