0

As the title says I'm stuggling with getting this to work. My code is not correct and I keep getting an error saying that basically everything in my function 'enter' is undefined.

My code:

from tkinter import Tk, Button, Label, Entry, END
from tkinter.messagebox import showinfo
import random
class Ed():
    'helps teach kids simple addition and subtraction'

    '''sets the problem in an (a operation b) setting
    in entry box 1. Number cannot be negative'''
    a = random.randrange(1,9)      #first number
    b = random.randrange(1,9)      #second number
    c = random.randrange(1,2)   #set the operation


    def enter():
        'checks the answer in entry 2 if it is correct'
        ans = eval(anwEnt.get())

        pEnt.delete(0, END)
        anwEnt.delete(0, END)

    root = Tk()

    # problem entry
    pEnt= Entry(root)
    pEnt.grid(row=1, column=1)
    if c == 1:
        pEnt.insert(END, '{} + {}'.format(a,b))
    if c == 2 and a > b:
        pEnt.insert(END, '{} - {}'.format(a,b))
    if b > a and c == 2:
        pEnt.insert(END, '{} - {}'.format(b,a))

    # answer entry
    anwEnt = Entry(root)
    anwEnt.grid(row=2, column=1)


    # Button
    button = Button(root, text = 'Enter', command=enter)
    button.grid(row=3, column=0, columnspan=2)

    root.mainloop()

I know that I need to use init but I really am not sure how to. Any help will be greatly appreciated.

Thanks in advance

falsetru
  • 357,413
  • 63
  • 732
  • 636
Andrew
  • 65
  • 1
  • 7

2 Answers2

0

i'm not familiar with Tkinter but here's an example in Gtk:

#!/usr/bin/env python3

import random
import gi
gi.require_version( 'Gtk', '3.0' )
from gi.repository import Gtk

class Ed( Gtk.Window ):
def __init__( self ):
    Gtk.Window.__init__( self )
    self.connect( 'destroy', lambda q: Gtk.main_quit() )

    self.pEnt = Gtk.Entry()
    self.anwEnt = Gtk.Entry()

    button = Gtk.Button( "Enter" )
    button.connect( "clicked", self.on_enter_button_clicked )

    grid = Gtk.Grid( )
    grid.set_row_spacing( 20 )
    grid.set_column_spacing( 20 )
    grid.attach( self.pEnt, 0, 0, 1, 1 )
    grid.attach( self.anwEnt, 0, 1, 1, 1 )
    grid.attach( button, 1, 0, 1, 3 )

    a = random.randrange(1,9)      #first number
    b = random.randrange(1,9)      #second number
    c = random.randrange(1,2)      #set the operation

    if c == 1:
        problem = '{} + {}'.format(a,b)
    elif  c == 2:
        if a > b:
            problem = '{} - {}'.format(a,b)
        else:
            problem = '{} - {}'.format(b,a)
    self.pEnt.set_text( problem )

    self.add( grid )
    self.show_all()

def on_enter_button_clicked( self, event ):
    correct_answer = eval( self.pEnt.get_text() )
    inputted_answer = int( self.anwEnt.get_text() )
    if inputted_answer == correct_answer:
        print( "Very Good:", inputted_answer )
    else:
        print( "Wrong! The Correct Answer is:", correct_answer )
    self.pEnt.set_text( "" )
    self.anwEnt.set_text( "" )

w = Ed()
Gtk.main()
0

indeed the preferred way to structure tkinter GUIs is using classes (you can check: Introduction to GUI programming with tkinter, and Best way to structure a tkinter application)

  • The __init__ function is automatically called when you create a new instance of a class.
  • The self variable refers to the newly created instance, and can be conveniently used to store data and references to the GUI's widgets.

In your case, the code could look something like this:

from tkinter import Tk, Button, Entry, END
from tkinter.messagebox import showinfo
import random

class Ed():
    """ helps teach kids simple addition and subtraction """
    def __init__(self):
        self.root = Tk()
        self.createWidgets()
        self.resetProblem()
        self.root.mainloop()

    def initialize_variables(self):
        """sets the problem in an (a operation b) setting
        in entry box 1. Number cannot be negative"""
        self.a = random.randrange(1,9)   #first number
        self.b = random.randrange(1,9)   #second number
        self.c = random.randrange(1,2)   #set the operation

    def createWidgets(self):
        # problem entry
        self.pEnt = Entry(self.root) 
        self.pEnt.pack()
        # answer entry
        self.anwEnt = Entry(self.root)
        self.anwEnt.pack()
        self.anwEnt.bind('<Return>', self.enter)
        # Button
        self.button = Button(self.root, text='Enter', command=self.enter)
        self.button.pack()

    def resetProblem(self):
        self.initialize_variables()
        self.pEnt.configure(state='normal')
        self.pEnt.delete(0,END)
        self.anwEnt.delete(0, END)
        if self.c == 1:
            self.pEnt.insert(0, '{} + {}'.format(self.a,self.b))
        if self.c == 2 and self.a > self.b:
            self.pEnt.insert(0, '{} - {}'.format(self.a,self.b))
        if self.b > self.a and self.c == 2:
            self.pEnt.insert(0, '{} - {}'.format(self.b,self.a))
        self.pEnt.configure(state='readonly') #kid doesn't need to edit the problem

    def enter(self, event=''):
        'checks if the answer in entry 2 is correct'
        try:
            ans = int(self.anwEnt.get())
            if ans == eval(self.pEnt.get()):
                showinfo("Yuhuu!", "Well done!")
                self.resetProblem()
            else:
                self.anwEnt.delete(0, END)
        except:
            self.anwEnt.delete(0, END)


# Launch the GUI
Ed()
Community
  • 1
  • 1
Josselin
  • 2,593
  • 2
  • 22
  • 35