0

So I'm trying to make an automatic TicTacToe GUI that will play you back once you move. The code you see is very layman as the actual code is very long and generally out of context. I want the code itself to work so that when the button is clicked, the value of A1 will change to 1 and it will check if the value is 1 so it can print, "This is a test" if so.

I've already tried global, I don't know if I'm doing it wrong or not. Is there any other way of doing this withought assigning a different Variable?

from tkinter import *
root = Tk()
A1 = 0
def btn_change():
    global A1
    A1 += 1
Button1 = Button(root, text="    ", command=btn_change)
Button1.pack()
if A1 == 1:
    print("This is a test.")
root.mainloop()

When I run the code, the window looks fine, but when I press the button on the screen, it doesn't display "This is a test." In other words, it's just blank.

1 Answer 1

1

Consider the below code:

if A1 == 1:
    print("This is a test.")

It runs exactly once before the mainloop starts. You will never reach the point where A1 reaches 1 and print the result.

What you need is a check for the variable A1 whenever you want, which can be done by creating another button:

Button(root, text="get result",command=lambda: print("This is a test.") if A1==1 else "").pack()
Sign up to request clarification or add additional context in comments.

3 Comments

Your description is slightly incorrect. It doesn't run during the init of mainloop. It runs before mainloop has started.
This seems like very helpful advice, but what if I wanted the variable to be updated when the button is clicked and have a conditional check to see if A1 = 1? Is it possible in python? I don't want to have a separate button because that would simply render my code an inconvenience. Thanks for your help on such a short note of time!
I am not entirely sure what do you mean, but obviously you could just move the if A1==1: print ("this is a test.") inside your bt_change function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.