Hello, in Tkinter how to take the value of the sum generated by numbers and compare with the user input?

Asked

Viewed 340 times

0

from tkinter import *
from random import randrange, uniform

window = Tk() 
window.title("Welcome to LikeGeeks app") 
window.geometry('800x600')

lbl1 = Label(window, text="00", font=("Arial Bold", 50)) 
lbl1.grid(column=0, row=0)
lbl2 = Label(window, text="00", font=("Arial Bold", 50)) 
lbl2.grid(column=0, row=1)
lbl3 = Label(window, text="+", font=("Arial Bold", 50)) 
lbl3.grid(column=3, row=0)
resposta = Entry(window,width=4, font=("Arial Bold", 50)) 
resposta.grid(column=0, row=2)

def proxima():
    a = randrange(10, 99) #faixa de inteiro
    b = randrange(10, 99) #faixa de inteiro
    lbl1.configure(text= str(a))
    lbl2.configure(text= str(b))
    soma = a+b
    print(soma)

def calculo():  
    print(soma) 
    if resposta.get() == soma:
        print("Acertou")
    else:
        print("Errou...")

btn = Button(window, text="Proxima", command=proxima)
btn.grid(column=0, row=3)
btn2 = Button(window, text="Calcular", command=calculo)
btn2.grid(column=0, row=4)
window.mainloop()

Relate the item

1 answer

0


Your question is not very clear. Tkinter has nothing to do with with sum of numbers, it is only a visual graphical interface for the user to interact. The part of adding up random numbers and comparing, you have to do in python same, and not in Tkinter.

Also you forgot to put the complete error you are receiving when you run your code. It is much easier to see the problem when you have the complete error. I suggest edit the question and add information to make it clearer.


As for the answer, it seems that you are using two variables called soma; one within the function proxima and another within the function resposta.

In python the variables are attached to the scope in which they were created; if you want to access a variable that is in another scope, you need to do this manually, and each function creates a scope of variables.

A direct way to solve would be to pass the variable soma for the overall scope.

def proxima():
    global soma
    # ... restante da função continua igual
  • Thanks friend! Even without understanding you gave me the answer I needed, "global sum", worked the way I wanted!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.