1

I am currently working on a projet similar to tic tac toe (with an AI) And I did a GUI to allow the user to play with the bot But the program doesn't wait for the player to choose and instead it crash because it doesn't have value

So I searcher about threads, tried for a long time can't achieve to figure out how it works I did some tests (bellow) that my archly resemble what I need to do with my code But it doesn't work neither Do someone have an answer ?

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```
Deltix
  • 35
  • 3
  • You need to work through a tutorial on responding to a button click. – Prune Apr 29 '20 at 19:25
  • ***`target = boucle()`***: Read [why-is-button-parameter-command-executed-when-declared](https://stackoverflow.com/questions/5767228) and [Tkinter understanding mainloop](https://stackoverflow.com/a/29158947/7414759) – stovfl Apr 29 '20 at 19:25
  • You definitely don't need threads for this. – Bryan Oakley Apr 29 '20 at 19:48
  • Are you aware of events in tkinter? You can bind a key to any event in tkinter. Threads aren't needed. – 10 Rep Apr 29 '20 at 20:45

1 Answers1

1

You don't need to use threads, just use events.

Say you wanted to bind a function to the enter key.

This would be your code:

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

You can read more about tkinter events here.

Hopefully this helps!

10 Rep
  • 2,217
  • 7
  • 19
  • 33
  • It really helps I think I am now searching about this but I tried event.isSet() with the "" and it doesn't work (obviously) but is there an equivalent ? I need to make my program stop until someone click a button and I didn't find anything about this anywhere – Deltix Apr 30 '20 at 08:38
  • I also found about update() instead of mainloop() and I thinks it's a big leap forward but there is still a problem about "waiting" for the user – Deltix Apr 30 '20 at 08:46
  • You don't need to use event.isSet(). Just use the bind function like listed above. If you need a bigger example I will edit my answer. – 10 Rep Apr 30 '20 at 16:09
  • I'd like please, I think I already understand how bind and the event works but I need a way to "stop a function until an event" instead of "starting when there is one" like in your example – Deltix Apr 30 '20 at 17:00