使用python 3.5.2中的类创建GUI

时间:2017-03-14 00:41:30

标签: python-3.x class user-interface tkinter

正如标题所说,我正在努力让它发挥作用。我的代码不正确,我不断收到错误,说我的函数'enter'中的所有内容基本上都是未定义的。

我的代码:

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

我知道我需要使用 init ,但我真的不知道该怎么做。 任何帮助将不胜感激。

提前致谢

2 个答案:

答案 0 :(得分:0)

我不熟悉Tkinter,但这是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()

答案 1 :(得分:0)

确实构造tkinter GUI的首选方法是使用类(您可以检查:Introduction to GUI programming with tkinterBest way to structure a tkinter application

  • 创建类的新实例时会自动调用__init__函数。
  • self变量引用新创建的实例,可以方便地用于存储数据和对GUI小部件的引用。

在您的情况下,代码可能如下所示:

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