我不能使用键盘上的等号或回车键来获得任何答案

时间:2014-09-25 11:05:02

标签: python tkinter

好吧我正在使用此代码用于教育目的,如果我去45 + 54并按Enter键我没有得到任何答案,但如果在屏幕上使用=不在我的键盘上它的工作原理。我是如此困难和压力,因为我做了这么多的研究,但没有找到我的答案。所有我要求的帮助是我错过了一段代码,阻止我在小键盘上使用等号键或回车键。请帮忙,这是代码:

   from tkinter import *
   import tkinter

# Calculator is a class derived from Frame.  Frames, being someone generic,
# make a nice base class for whatever you what to create.
class Calculator(Frame):

# Create and return a packed frame.
def frame(this, side): 
    w = Frame(this)
    w.pack(side=side, expand=YES, fill=BOTH)
    return w

# Create and return a button.
def button(this, root, side, text, command=None): 
    w = Button(root, text=text, command=command) 
    w.pack(side=side, expand=YES, fill=BOTH)
    return w

# Enter a digit.
need_clr = False
def digit(self, digit):
    if self.need_clr:
        self.display.set('')
        self.need_clr = False
    self.display.set(self.display.get() + digit)

# Change sign.
def sign(self):
    need_clr = False
    cont = self.display.get()
    if len(cont) > 0 and cont[0] == '-':
        self.display.set(cont[1:])
    else:
        self.display.set('-' + cont)

# Decimal
def decimal(self):
    self.need_clr = False
    cont = self.display.get()
    lastsp = cont.rfind(' ')
    if lastsp == -1:
        lastsp = 0
    if cont.find('.',lastsp) == -1:
        self.display.set(cont + '.')

# Push a function button.
def oper(self, op):
    self.display.set(self.display.get() + ' ' + op + ' ')
    self.need_clr = False

# Calculate the expressoin and set the result.
def calc(self):
    try:
        self.display.set(eval(self.display.get()))
        self.need_clr = True
    except:
        showerror('Operation Error', 'Illegal Operation')
        self.display.set('')
        self.need_clr = False

def Enter(self):
    self.display.set('Enter')

def keyPressed(self,event):
    if event.keysym == 'Enter':
        self.enter()   

def __init__(self):
    Frame.__init__(self)
    self.option_add('*Font', 'Verdana 12 bold')
    self.pack(expand=YES, fill=BOTH)
    self.master.title('Simple Calculator')

    # The StringVar() object holds the value of the Entry.
    self.display = StringVar()
    e = Entry(self, relief=SUNKEN, textvariable=self.display)
    e.pack(side=TOP, expand=YES, fill=BOTH)

    # This is a nice loop to produce the number buttons.  The Lambda
    # is an anonymous function.
    for key in ("123", "456", "789"):
        keyF = self.frame(TOP)
        for char in key:
            self.button(keyF, LEFT, char,
                        lambda c=char: self.digit(c))

    keyF = self.frame(TOP)
    self.button(keyF, LEFT, '-', self.sign)
    self.button(keyF, LEFT, '0', lambda ch='0': self.digit(ch))
    self.button(keyF, LEFT, '.', self.decimal)

    # The frame is used to hold the operator buttons.
    opsF = self.frame(TOP)
    for char in "+-*/=":
        if char == '=':
            btn = self.button(opsF, LEFT, char, self.calc)
        else:
            btn = self.button(opsF, LEFT, char, 
                              lambda w=self, s=char: w.oper(s))

    # Clear button.
    clearF = self.frame(BOTTOM)
    self.Enter_button = self.button(clearF, LEFT, 'Enter', self.Enter)
    self.bind_all('<Key>', self.keyPressed)

# Make a new function for the - sign.  Maybe for . as well.  Add event
# bindings for digits to call the button functions.

# This allows the file to be used either as a module or an independent
# program.
if __name__ == '__main__':
Calculator().mainloop()

1 个答案:

答案 0 :(得分:0)

要在按键上调用与按钮相同的功能,您必须将按键绑定到GUI。

实施例

try:
    # for Python2
    from Tkinter import *
except ImportError:
    # for Python3
    from tkinter import *


class GUI(Frame):

    # Create and return a packed frame.
    def frame(self, side): 
        w = Frame(self)
        w.pack(side=side, expand=YES, fill=BOTH)
        return w

    # Create and return a button.
    def button(self, root, side, text, command=None): 
        w = Button(root, text=text, command=command) 
        w.pack(side=side, expand=YES, fill=BOTH)
        return w

    def hello(self):
        self.display.set('hello')

    def keyPressed(self,event):
        #test to see whether enetr is pressed
        if event.keysym == 'Return':
            self.hello()
    def __init__(self):
        Frame.__init__(self)
        self.option_add('*Font', 'Verdana 12 bold')
        self.pack(expand=YES, fill=BOTH)
        self.master.title('Simple GUI')

        # The StringVar() object holds the value of the Entry.
        self.display = StringVar()
        e = Entry(self, relief=SUNKEN, textvariable=self.display)
        e.pack(side=TOP, expand=YES, fill=BOTH)


        # Clear button.
        clearF = self.frame(BOTTOM)
        self.hello_button = self.button(clearF, LEFT, 'Hello', self.hello)
        #bind keypresses
        self.bind_all('<Key>', self.keyPressed)


if __name__ == '__main__':
 GUI().mainloop()

对于这个具体的例子,下面的代码可以起作用:

try:
    # for Python2
    from Tkinter import *
except ImportError:
    # for Python3
    from tkinter import *
    # Calculator is a class derived from Frame.  Frames, being someone generic,
    # make a nice base class for whatever you what to create.
# Calculator is a class derived from Frame.  Frames, being someone generic,
        # make a nice base class for whatever you what to create.
class Calculator(Frame):

    # Create and return a packed frame.
    def frame(this, side): 
        w = Frame(this)
        w.pack(side=side, expand=YES, fill=BOTH)
        return w

    def keyPressed(self,event):
        #test to see whether enetr is pressed
        if event.keysym == 'Return':
            self.calc()

    # Create and return a button.
    def button(this, root, side, text, command=None): 
        w = Button(root, text=text, command=command) 
        w.pack(side=side, expand=YES, fill=BOTH)
        return w

    # Enter a digit.
    need_clr = False
    def digit(self, digit):
        if self.need_clr:
            self.display.set('')
            self.need_clr = False
        self.display.set(self.display.get() + digit)

    # Change sign.
    def sign(self):
        need_clr = False
        cont = self.display.get()
        if len(cont) > 0 and cont[0] == '-':
            self.display.set(cont[1:])
        else:
            self.display.set('-' + cont)

    # Decimal
    def decimal(self):
        self.need_clr = False
        cont = self.display.get()
        lastsp = cont.rfind(' ')
        if lastsp == -1:
            lastsp = 0
        if cont.find('.',lastsp) == -1:
            self.display.set(cont + '.')

    # Push a function button.
    def oper(self, op):
        self.display.set(self.display.get() + ' ' + op + ' ')
        self.need_clr = False

    # Calculate the expressoin and set the result.
    def calc(self):
        try:
            self.display.set(eval(self.display.get()))
            self.need_clr = True
        except:
            showerror('Operation Error', 'Illegal Operation')
            self.display.set('')
            self.need_clr = False

    def __init__(self):
        Frame.__init__(self)
        self.option_add('*Font', 'Verdana 12 bold')
        self.pack(expand=YES, fill=BOTH)
        self.master.title('Simple Calculator')

        # The StringVar() object holds the value of the Entry.
        self.display = StringVar()
        e = Entry(self, relief=SUNKEN, textvariable=self.display)
        e.pack(side=TOP, expand=YES, fill=BOTH)

        # This is a nice loop to produce the number buttons.  The Lambda
        # is an anonymous function.
        for key in ("123", "456", "789"):
            keyF = self.frame(TOP)
            for char in key:
                self.button(keyF, LEFT, char,
                            lambda c=char: self.digit(c))

        keyF = self.frame(TOP)
        self.button(keyF, LEFT, '-', self.sign)
        self.button(keyF, LEFT, '0', lambda ch='0': self.digit(ch))
        self.button(keyF, LEFT, '.', self.decimal)

        # The frame is used to hold the operator buttons.
        opsF = self.frame(TOP)
        for char in "+-*/=":
            if char == '=':
                btn = self.button(opsF, LEFT, char, self.calc)
            else:
                btn = self.button(opsF, LEFT, char, 
                                  lambda w=self, s=char: w.oper(s))

        # Clear button.
        clearF = self.frame(BOTTOM)
        self.button(clearF, LEFT, 'Clr', lambda w=self.display: w.set(''))
        self.bind_all('<Key>', self.keyPressed)
     # Make a new function for the - sign.  Maybe for . as well.  Add event
     # bindings for digits to call the button functions.

     # This allows the file to be used either as a module or an independent
     # program.
if __name__ == '__main__':
    Calculator().mainloop()