Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

i'm trying to make a number guesser so when the button is pressed it should begin the game, the button works but the game will not begin

it should make a windows and create a button which it does but when i click it it does not begin the game my code is:

from tkinter import *

a = False
import random
def start():
    a = True

window = Tk()
window.geometry("500x500")
btn = Button(window, text="Want to play a game?", bd = "5", command = start )
btn.pack(side = 'top')
window.mainloop()

if a == True:
    s = random.randint(1,4)
    t = int(input("Pick a number 1-4: "))
    if t != s:
        print("You lose!")
    else:
        print("You win!")

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You cannot change a global variable in a function except using the global keyword, because instead it will create a new local variable.

Also, the if statement will only run after the window is closed because the mainloop() function is running that whole time – instead just put all the code for the game in the start() function.

Code:

import random

def start():
    s = str(random.randint(1,4))
    t = input("Pick a number 1-4: ")
    if t != s:
        print("You lose!")
    else:
        print("You win!")

window = Tk()
window.geometry("500x500")
btn = Button(window, text="Want to play a game?", bd = "5", command = start )
btn.pack(side = 'top')
window.mainloop()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading