I want to change background color of complete canvas whenever a mouse hovers over it. Have this code for it. Minimal Example:
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()
Color of canvas changes to red when mouse is pointed over it, if it's empty (see commented line). However if I try to add a text, or any other widget on canvas, the program stops working and throws a cryptic error.
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
What is this error? Is there any way to change background color of canvas on cursor hover while also having other widgets/text in it ?
Any help appreciated. Thanks
Your class inherits from tk.Canvas
class HoverCanvas(tk.Canvas):
but you call the __init__
method of tk.Frame
tk.Frame.__init__(self,master=master,**kw)
You should call the __init__
method of tk.Canvas
instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.