【问题标题】:tkinter button only visible when a word is in a textbox pythontkinter 按钮仅在单词在文本框 python 中时可见
【发布时间】:2021-09-28 15:52:39
【问题描述】:

我正在尝试在 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()

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

【问题讨论】:

  • "1,0" 应该是"1.0",你为什么使用 Python 2.x?这是一个不推荐使用的版本,不应该使用,第二:我强烈建议在导入某些东西时不要使用通配符 (*),你应该导入你需要的东西,例如from module import Class1, func_1, var_2 等等或导入整个模块:import module 然后你也可以使用别名:import module as md 或类似的东西,关键是不要导入所有东西,除非你真的知道你在做什么;名称冲突是问题所在。当你打包按钮集active = False 并且不需要它是全局的
  • 使用threadingtkinter 不是一个好主意。有时tkinter 从另一个线程调用它可能会崩溃。

标签: python multithreading tkinter button find


【解决方案1】:

您不需要使用线程来执行此操作,您可以使用 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,它绑定到&lt;KeyRelease&gt;,这是用户释放键的时候。然后在释放键时调用check_for_word。 (lambda 部分是忽略事件参数)。 check_for_word 然后做之前做的事情。

【讨论】:

  • 为什么不加else: save_button.pack_forget()?我认为 OP 会想要那个。
  • 好主意,我错过了。谢谢
  • 我使用 save_button.place 代替 pack_forget,所以我需要使用 save_button.place_forget
  • 很高兴我能帮上忙,是的,你需要place_forget
【解决方案2】:

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

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

对于 while 循环,您不一定需要全局变量,如果您希望它不断检查条件(如果您希望按钮在用户取消单词后消失),则可以使用 while True:

【讨论】:

    猜你喜欢
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-20
    • 2019-02-03
    • 2021-05-17
    • 1970-01-01
    相关资源
    最近更新 更多