Change text color when hovering over text with Tkinter?

So, I have a bunch of text on canvas in Tkinter, and I want to make the text color change when the mouse hovers over the text. For life, I can’t understand how to do this, and there seems to be not much information about Tkinter.

for city in Cities:
    CityText = Cities[i]
    board.create_text(CityLocs[CityText][0], CityLocs[CityText][1], text=CityText, fill="white")
    CityText = Cities[i]
    i = i + 1

This is just my code to put text on the canvas, although I'm not sure what else needs to be published to get my point. Is there a freeze function or something similar built into Tkinter?

+5
source share
3 answers

Here (admittedly) is a rather lame example that works on OS-X ...

from Tkinter import *

master=Tk()
canvas=Canvas(master)
canvas.pack()
canvas.create_text((20,20),activefill="red",text="Hello World!",fill="black")
master.mainloop()

link: http://effbot.org/tkinterbook/canvas.htm

+3
source

(, , , , ) Tkinter.

- http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm -

, , :

import Tkinter
from functools import partial

def color_config(widget, color, event):
    widget.configure(foreground=color)

parent = Tkinter.Tk()
text = Tkinter.Label(parent, text="Hello Text")
text.bind("<Enter>", partial(color_config, text, "red"))
text.bind("<Leave>", partial(color_config, text, "blue"))
text.pack()

Tkinter.mainloop()

functools.partial Text (Label), . , , , -, , for. functools.partial "" .

, Canas, "fill" "fillactive" , @mgilson, , , .

__call__, bind , . :

from Tkinter import *

class Follower(object):
    def __init__(self,on_color="#fff", off_color="#000"):
        self.on_color = on_color
        self.off_color = off_color
        self.previous_item = None
    def hover(self, canvas, item, x, y):
        x1, y1, x2, y2 = canvas.bbox(item)
        if x1 <= x <= x2 and y1 <= y <= y2:
            return True
        return False

    def __call__(self, event):
        canvas = event.widget
        item = canvas.find_closest(event.x, event.y)
        hovering = self.hover(canvas, item, event.x, event.y)
        if (not hovering or item != self.previous_item) and self.previous_item is not None:
            canvas.itemconfig(self.previous_item, fill=self.off_color)
        if hovering:
            canvas.itemconfig(item, fill=self.on_color)
        self.previous_item = item

master=Tk()
canvas=Canvas(master)
canvas.pack()
canvas.create_text((40,20),text="Hello World!",fill="black")
canvas.create_text((60,80),text="FooBar",fill="black")
canvas.bind("<Motion>", Follower())
master.mainloop()

( , @mgilson)

+2

Tkinter. "activefill", , , .

See the following link for more information. Effbot.org/tkinterbook is my transition to tkinter. http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.create_text-method

+1
source

All Articles