简体   繁体   English

if 条件在 Tkinter 中没有按预期工作

[英]The if condition does not work as expected in Tkinter

I've been having some troubles with this code as the if condition cannot be true and always executes the else condition instead.我在这段代码中遇到了一些问题,因为 if 条件不能为真,而是总是执行 else 条件。

can you help `你能帮忙`

from tkinter import *

root = Tk()

entry_1 =Entry(root, width = 20)
entry_1.pack()
entry_1.insert(0, "Choose Your Number ")


def m():
    answer = entry_1.get().strip()
    if answer == 5 :
        mylabel = Label(root, text = "YOU WIN!")
        mylabel.pack()
    else :
        mylabel = Label(root, text = "YOU LOST!")
        mylabel.pack()


mybutton = Button(root, text = 'PLAY', command = m)
mybutton.pack()


root.mainloop()

Thanks谢谢

Any user input is a string, so you need to convert to an Integer.任何用户输入都是字符串,因此您需要转换为 Integer。

Try this code:试试这个代码:

from tkinter import *

root = Tk()

entry_1 =Entry(root, width = 20)
entry_1.pack()
entry_1.insert(0, "Choose Your Number ")


def m():
    answer = int(entry_1.get().strip())
    if answer == 5 :
        mylabel = Label(root, text = "YOU WIN!")
        mylabel.pack()
    else :
        mylabel = Label(root, text = "YOU LOST!")
        mylabel.pack()


mybutton = Button(root, text = 'PLAY', command = m)
mybutton.pack()


root.mainloop()
 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM