简体   繁体   English

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

[英]Unable to change tkinter Canvas background color on mouse hover?

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 您的课程继承自tk.Canvas

class HoverCanvas(tk.Canvas):

but you call the __init__ method of tk.Frame 但您调用tk.Frame__init__方法

tk.Frame.__init__(self,master=master,**kw)

You should call the __init__ method of tk.Canvas instead. 您应该改为调用tk.Canvas__init__方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM