Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading