如何根据鼠标移动多次配置标签中的文本? Python、Tkinter

问题描述 投票:0回答:2

我想根据鼠标位置 () 修改我的标签并且它有效但只有一次。每次我的鼠标改变位置时我该怎么做? 下面的代码只修改了我的标签一次。如果您能看看我的代码并告诉我哪里出了问题,我将不胜感激!谢谢!

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()

我用 if、elif 尝试了不同的东西,并尝试修改范围。它仍然只工作一次。

python user-interface tkinter label
2个回答
0
投票

不确定为什么需要将 if 语句包装为字符串。下面对我有用。

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 event.x>430:
        l1.config(text="Hello")
    if 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()

0
投票

您的代码的问题是您正在转换比较 event.x > 430 和 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.

要解决此问题,您应该从 if 语句中删除 str() 函数调用。 change_me 功能像其他人说的应该没问题:

def change_me(event):
    if event.x > 430:
        l1.config(text="Hello")
    if event.x < 430: 
        l1.config(text="Hi")
© www.soinside.com 2019 - 2024. All rights reserved.