0

I'm trying to make a simple math thing that when you give the right answer it says 'correct' and when you get it wrong it says 'wrong'; however, it gives an error:

Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\yu.000\AppData\Local\Programs\Python\Python38-32\lib\tkinter_init_.py", line 1883, in call return self.func(*args) TypeError: check() missing 1 required positional argument: 'entry'

and here's the code:

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()
M-Chen-3
  • 2,036
  • 5
  • 13
  • 34
Walt Fu
  • 11
  • 3

1 Answers1

4

First of all, you need to import tkinter as tk, otherwise tk is undefined.

Next, your line here:

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

should be replaced with:

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

Let me explain how this works.

  1. You can't just pass check to the button, since check requires an entry parameter. You can get around this by defining a lambda function that calls check(entry).

  2. To get the input from the entry widget, you do entry.get(); however, since entry stores the input as a string, you must convert it to an integer using int() in order to compare it to 22.

The full code is below:

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()
M-Chen-3
  • 2,036
  • 5
  • 13
  • 34