0

Please help me with this code, ven if i enter the correct answer that is \'9'\ in user_input, the messagebox i am getting is "You Have Lost", instead of "You Have Won".

Any help will be appreciated, thank you all.

from tkinter import *
from tkinter import messagebox

magic = str(9)
rt = Tk()

def roll():
    if user_input == magic:
        messagebox._show("Congratulation", "You Have Won!!")
    else:
        messagebox._show("Try Again", "You Have Lost!!")

label1 = Label(rt , text = "Enter Your Number Here: ").pack()
user_input = Entry(rt).pack()
btn1 = Button(rt, text = "Click", command = roll).pack()

rt.mainloop()
1
  • the value of user_input is None and that of magic is 9, hence the if condition is bound to fail Commented Apr 5, 2020 at 18:13

2 Answers 2

1

Your user_input is None since pack() method returns None and you are setting it equal to user_input. One way to resolve this is to get the text value of the entry within the function.

from tkinter import*
from tkinter import messagebox

magic = str(9)
rt = Tk()


def roll():
    user_input = entry.get()  # getting the text value of the entry widget
    if user_input == magic:
        messagebox._show("Congratulation", "You Have Won!!")
    else:
        messagebox._show("Try Again", "You Have Lost!!")


label1 = Label(rt, text="Enter Your Number Here: ").pack()
entry = Entry(rt)  # set this equal to the variable, not with the execution of pack()
entry.pack()
btn1 = Button(rt, text="Click", command=roll).pack()

rt.mainloop()
Sign up to request clarification or add additional context in comments.

Comments

1

don't write Entry.pack()

Entry is class, it creates an instance (let's call it i1)
by executing it.pack() you place it on the window, but return None

so basically you're saying

Entry().pack()
user_input = None

save Entry instance in the variable (say e1)
and get user_input inside roll function by
user_uinput = e1.get()

also, I recommend using oop to work with tkinter, but it's ok to start without

Comments

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.