Search code examples
pythonuser-interfacetkinterlabel

How to config my text in label based on mouse motion many times? Python, Tkinter


I want to modify my label based on mouse position () and it works but only one time. How can I do this every time my mouse changes position? The code below modifies my label only one time. I would appreciate if you could take a look at my code and tell me what is wrong! Thank you !

import tkinter as tk
window=tk.Tk()
window.title("Labels")
window.geometry("850x600")
window.resizable(width=False, height=False)
#create main function
def change_me(event):
    if str(event.x>430):
        l1.config(text="Hello")
    if str(event.x<430): 
        l1.config(text="Hi")
#label I wanna modify
l1=tk.Label(width=500, height=500, text="to display")
l1.pack()
window.bind('<Motion>', change_me)

window.mainloop()

I tried different things with if, elif and tried to modify scopes. It still works only once.


Solution

  • The issue with your code is that you are converting the result of the comparison event.x > 430 and event.x < 430 to a string before checking it in the if statements. This means that the conditions will always evaluate to True, since non-empty strings are considered truthy in Python.

    To fix this, you should remove the str() function calls from your if statements. change_me function like the other guy said should be fine:

    def change_me(event):
        if event.x > 430:
            l1.config(text="Hello")
        if event.x < 430: 
            l1.config(text="Hi")