【问题标题】:How do you wait for an user to click a tkinter button with threads您如何等待用户单击带有线程的 tkinter 按钮
【发布时间】:2020-04-29 19:01:24
【问题描述】:

我目前正在开发一个类似于 tic tac toe 的项目(使用 AI) 我做了一个 GUI 让用户可以玩这个机器人 但是程序并没有等待玩家选择而是因为没有价值而崩溃

所以我搜索线程,尝试了很长时间无法弄清楚它是如何工作的 我做了一些测试(如下),我的代码类似于我需要对我的代码做的事情 但它也不起作用 有人有答案吗?

import threading
import tkinter as tk

windo = tk.Tk()
windo.title("Morpion")
windo.resizable(width=tk.FALSE, height=tk.FALSE)

class Player:
    def __init__(self,name):
        self.name = name
        self.choice = None

def Change_Var(x):
    print(P.choice)
    P.choice = x
    print(P.choice)
    play_event.set()

def boucle():
    i = 0
    while not play_event.isSet() and i < 3000:
        print(i)
        i += 1

P = Player("Deltix")
start = tk.Button(height=2,width=8, text = "Start",command = lambda x = 0 : Change_Var(x))
start.grid(column = 2, row = 3,pady = 5)

play_event = threading.Event()
threading.Thread(target = windo.mainloop()).start
threading.Thread(target = boucle()).start```

【问题讨论】:

标签: python multithreading events tkinter


【解决方案1】:

您不需要使用线程,只需使用事件即可。

假设您想将一个函数绑定到回车键。

这将是您的代码:

canvas = Canvas(master)
def clicked(event):
    print("Enter was pressed")
canvas.bind("<Return>", clicked)

您可以阅读更多关于 tkinter 事件 here 的信息。

希望这会有所帮助!

【讨论】:

  • 这真的很有帮助,我想我现在正在搜索这个,但我尝试了带有“”的 event.isSet() 并且它不起作用(显然)但是有没有等效的?我需要让我的程序停止,直到有人单击一个按钮并且我在任何地方都没有找到任何关于此的信息
  • 我还发现了关于 update() 而不是 mainloop() 的信息,我认为这是一个很大的飞跃,但仍然存在“等待”用户的问题
  • 你不需要使用 event.isSet()。只需使用上面列出的绑定功能。如果您需要更大的示例,我将编辑我的答案。
  • 我想拜托,我想我已经了解绑定和事件是如何工作的,但我需要一种方法来“停止一个函数直到一个事件”而不是“当有一个函数时开始”你的榜样
猜你喜欢
  • 1970-01-01
  • 2019-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多