【问题标题】:Python Issue with tkintertkinter 的 Python 问题
【发布时间】:2020-04-05 18:04:22
【问题描述】:

请帮助我使用此代码,即使我在user_input 中输入正确的答案是\'9'\,我得到的messagebox 是“你输了”,而不是“你赢了” .

任何帮助将不胜感激,谢谢大家。

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()

【问题讨论】:

  • user_input的值为Nonemagic的值为9,所以if条件必然失败

标签: python tkinter output


【解决方案1】:

您的user_inputNone,因为pack() 方法返回None 并且您将其设置为等于user_input。 解决此问题的一种方法是获取函数中条目的文本值。

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()

【讨论】:

    【解决方案2】:

    不要写Entry.pack()

    Entry 是类,它创建一个实例(我们称之为i1
    通过执行it.pack()你将它放在窗口上,但返回None

    所以基本上你是在说

    Entry().pack()
    user_input = None
    

    Entry 实例保存在变量中(比如e1
    并通过
    user_uinput = e1.get()

    获取 user_input inside roll 函数

    另外,我建议使用 oop 与 tkinter 一起工作,但不使用也可以

    【讨论】:

      猜你喜欢
      • 2014-09-20
      • 2016-05-25
      • 2018-05-17
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 2017-08-14
      • 2018-02-14
      • 2021-06-20
      相关资源
      最近更新 更多