我正在尝试做一个简单的数学运算,但它给了我一个错误

时间:2021-02-17 16:26:37

标签: python tkinter tkinter-button

我正在尝试做一个简单的数学运算,当你给出正确答案时,它会说“正确”,而当你答错时,它会说“错误”;但是,它给出了一个错误:

<块引用>

Tkinter 回调中的异常 回溯(最近一次调用最后一次): 文件“C:\Users\yu.000\AppData\Local\Programs\Python\Python38-32\lib\tkinter_init_.py”,第 1883 行,调用 返回 self.func(*args) 类型错误:check() 缺少 1 个必需的位置参数:'entry'

这是代码:

import tkinter as tk

import tkinter.messagebox as tkm

window = tk.Tk()

window.title('my tk')

window.geometry('550x450')

def math1():

    e = tk.Tk()

    e.geometry('200x150')

    tk.Label(e, text = '10', height = 2).pack()

    tk.Label(e, text = '+ 12', height = 2).place(x=80, y=25)

    er = tk.StringVar()

    def check(entry):

        if entry == 22:

            tkm.showinfo('correct', 'correct!')

        else:

            tkm.showerror('try again', 'wrong, try again')
            
    entry = tk.Entry(e, textvariable = er)

    entry.place(x=90,y=60)

    tk.Button(e, text = 'submit', command = check).place(x=80, y = 80)

tk.Button(window, text='1', command = math1).pack()

window.mainloop()

1 个答案:

答案 0 :(得分:4)

首先需要import tkinter as tk,否则tk是未定义的。

接下来,您的线路在这里:

tk.Button(e, text = 'submit', command = check).place(x=80, y = 80)

应替换为:

tk.Button(e, text = 'submit', command = lambda: check(int(entry.get()))).place(x=80, y = 80)

让我解释一下这是如何工作的。

  1. 您不能只将 check 传递给按钮,因为 check 需要一个 entry 参数。您可以通过定义一个调用 lambdacheck(entry) 函数来解决这个问题。

  2. 要从 entry 小部件获取输入,您需要执行 entry.get();但是,由于 entry 将输入存储为字符串,因此您必须使用 int() 将其转换为整数才能将其与 22 进行比较。

完整代码如下:

import tkinter.messagebox as tkm
import tkinter as tk

window = tk.Tk()

window.title('my tk')

window.geometry('550x450')

def math1():

    e = tk.Tk()

    e.geometry('200x150')

    tk.Label(e, text = '10', height = 2).pack()

    tk.Label(e, text = '+ 12', height = 2).place(x=80, y=25)

    er = tk.StringVar()

    def check(entry):

        if entry == 22:

            tkm.showinfo('correct', 'correct!')

        else:

            tkm.showerror('try again', 'wrong, try again')
            
    entry = tk.Entry(e, textvariable = er)

    entry.place(x=90,y=60)

    tk.Button(e, text = 'submit', command = lambda: check(int(entry.get()))).place(x=80, y = 80)

tk.Button(window, text='1', command = math1).pack()

window.mainloop()