tkinter 按钮仅在文字位于文本框中时可见 python

tkinter button only visible when a word is in a textbox python

我正在尝试在 Tkinter 中创建一个按钮,只有当它在文本框中找到单词“hello”时才会出现(变得可见)。

我可以想象使用线程和全局变量,但我不知道如何编码, 我想象过类似的东西:

import Tkinter as *
from threading import Thread

window = Tk()
active = True

def check_for_word():
    global active
    textbox1 = textbox.get("1,0", "end")
    while active == True:
         if "hello" in textbox1:
              button.pack()
         else:
              button.pack_forget()

save_button = Button(window)

textbox = scrolledtext.ScrolledText(window)
textbox.pack()

threading = Thread (target=check_for_word)
threading.start()

window.mainloop()

这是我怀疑可以工作但最终没有的东西,按钮根本没有显示,就像代码甚至没有 运行,或者线程不能正常工作。那么我做错了什么,如果是这样,你能帮帮我吗?谢谢!

您必须将 textbox1 赋值放在 while 循环内和 if 条件之前,否则它会在进入循环前检查一次值,并始终检查相同的值。

我还想指出,in 运算符区分大小写,return True 如果它在变量中找到 a substring正在检查,而不仅仅是精确的单个单词(但我不确定这是否是有意的)。

对于while循环你不一定需要一个全局变量,你可以只使用while True:如果你想让它不断地检查条件(如果你想让按钮在用户取消后消失字)。

您不需要使用线程来执行此操作,您可以改用 tkinter 事件绑定。

def check_for_word():
    if "hello" in textbox.get("1.0", "end"):
        save_button.pack()
    else:
        save_button.pack_forget()

save_button = Button(window)

textbox = scrolledtext.ScrolledText(window)
textbox.bind("<KeyRelease>", lambda event:check_for_word())
textbox.pack()

要进行绑定,请使用 widget.bind。在这种情况下,小部件是 textbox 并且它绑定到 <KeyRelease>,这是用户释放按键的时间。然后在释放键时调用 check_for_word。 (lambda部分是忽略事件参数)。 check_for_word 然后做它之前做的事情。