Random number generator in Python Canvas

37 Views Asked by At

Hi I need help with this project to school. Everything is woriking but part where I ask in terminal what was number it always print it was't that number.

import tkinter
import random


canvas = tkinter.Canvas(width=800, height=400)
canvas.pack()

number = canvas.create_text(400, 200, text=random.randint(10000, 100000))

def prec():
    canvas.create_rectangle(400 - 50, 200 - 50, 400 + 50, 200 + 50, outline="white", fill="white")
canvas.after(2000, prec)

guess = input("What number was there?: ")
guess = int(guess)


if guess == number:
    canvas.create_text(400, 100, text="Correct", font="arial 20")
else:
    canvas.create_text(400, 100, text="Incorrect", font="arial 20")


canvas.mainloop()

Everytime I try it says "Incorrect" but it' correct. I don't know what to do to make it work so any help would be appreciated

1

There are 1 best solutions below

0
Yarin_007 On

the variable number is an object ID of a text object.

number = canvas.create_text(400, 200, text=random.randint(10000, 100000))

so you're not comparing the guess with the number displayed, but rather with that object ID. (which also happens to be an int [per the tkinter docs] but that's beside the point)

what you want is maybe to generate the number first, then use it in the canvas and in your value comparison.

import tkinter
import random


canvas = tkinter.Canvas(width=800, height=400)
canvas.pack()

# generate number
random_number = random.randint(10000, 100000)

# place number in canvas
number = canvas.create_text(400, 200, text=random_number)

def prec():
    canvas.create_rectangle(400 - 50, 200 - 50, 400 + 50, 200 + 50, outline="white", fill="white")
canvas.after(2000, prec)

guess = input("What number was there?: ")
guess = int(guess)


# compare guess to number
if guess == random_number :
    canvas.create_text(400, 100, text="Correct", font="arial 20")
else:
    canvas.create_text(400, 100, text="Incorrect", font="arial 20")

canvas.mainloop()

if the future, consider using a debugger to see the values of all variables