比较tkinter条目与实际加法ans

2024-09-28 21:54:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将输入框的输入与实际答案进行比较。这是我的第一个python项目,我仍然很困惑,说实话,我甚至不知道如何开始问这个问题。在

用户将单击加法或减法按钮。将出现一个字符串,询问“4+5等于什么?”这些数字是随机产生的。在

然后使用tkinter库插入一个输入框。我不知道如何get()输入并将其与实际数字的和或差进行比较。

我试图遵循这个video,但我也未能使用其他方法。仅供参考,我主要关注加法方法,所以如果你测试,先用加法。在

from tkinter import Entry
import tkinter as tk
import random as rand

root = tk.Tk()
root.geometry("450x450+500+300")
root.title("Let's play Math!")

welcomeLabel = tk.Label(text="LET'S PLAY MATH!").pack()
startLabel = tk.Label(text='Select a math operation to start').pack()

def addition():
    a = rand.randrange(1,10,1)
    b = rand.randrange(1,10,1)
    global Answer
    Answer = a + b

    tk.Label(text="What does " + str(a) + " + " + str(b) + " equal? ").place(x=0, y=125)
    global myAnswer
    myAnswer = Entry().place(x=300, y= 125)

def checkAnswer():
    entry = myAnswer.get()

    while int(entry) != Answer:
        if int(entry) != Answer:
            tk.Label(text="Let's try again.").pack()
        elif int(entry) == Answer:
            tk.Label(text="Hooray!").pack()


addBtn = tk.Button(text="Addition", command=addition).place(x=100, y = 60)
subBtn = tk.Button(text="Subtraction", command=subtraction).place(x=200, y=60)
checkBtn = tk.Button(text="Check Answer", command=checkAnswer).place(x=300, y = 150)

tk.mainloop()

Tags: textanswerimporttkinterplacebuttonrootlabel
3条回答

要解决问题,只需将Entry()对象的创建与放置分开:

def addition():
    a = rand.randrange(1,10,1)
    b = rand.randrange(1,10,1)
    global Answer
    Answer = int(a + b)

    tk.Label(text="What does " + str(a) + " + " + str(b) + " equal? ").place(x=0, y=125)
    global myAnswer
    myAnswer = Entry()
    myAnswer.place(x=300, y= 125)

{{cd3>返回一个.place()时,您将返回其结果,即None。因此,您从未在变量中实际存储Entry对象。在

另外,最好确保Answer也是int。在

考虑一下this,下面是一个示例,当用户单击answer_btn时,它将响应输入到answer的数字是"Correct!"还是{}:

import tkinter as tk
import random as rand

def is_correct():
    global answer, check
    if answer.get() == str(a + b):
        check['text'] = "Correct!"
    else:
        check['text'] = "False!"

def restart():
    global question, check
    random_nums()
    question['text'] = "{}+{}".format(a, b)
    check['text'] = "Please answer the question!"

def random_nums():
    global a, b
    a = rand.randrange(1, 10, 1)
    b = rand.randrange(1, 10, 1)

root = tk.Tk()

#create widgets
question = tk.Label(root)
answer = tk.Entry(root, width=3, justify='center')
check = tk.Label(root)
tk.Button(root, text="Check", command=is_correct).pack()
tk.Button(root, text="New question", command=restart).pack()

#layout widgets
question.pack()
answer.pack()
check.pack()

restart()
root.mainloop()

获取答案do answer = myanswer.get()或任何其他变量名的值。把它与正确答案作比较

if int(answer) == correctAnswer:
   #the code

你就是这么问的吗?在

相关问题 更多 >