如何退格并清除最后一个等式以及退出按钮?

时间:2013-12-01 22:25:46

标签: python tkinter

我试过了:

self.btnquit = button(calc_frame, "Quit", tk.destroy)
self.btnquit.pack(side = LEFT)

在self.input = ...

之前

但它出现了无效的语法。退格只有在数字前面才有效,但我希望它能够输入最后输入的数字,清除最后一个等式然后:

  from tkinter import *
    from tkinter.font import Font
    def button(frame, text, command=None):
        ft = Font(family=('Verdana'), size=14)
        return Button(frame, text=text, font=ft, width=3, command=command)
    def frame(frame, side=LEFT, bg="black"):
        f = Frame(frame, background=bg, padx=5, pady=5)
        f.pack(side=side, expand=YES, fill=BOTH)
        return f
    class App:
        def __init__(self, tk):
            ft = Font(family=('Verdana'), size=14)
            main = frame(tk)
            l_frame = frame(main)
            r_frame = frame(main)
            calc_frame = frame(l_frame)
            self.input = Entry(calc_frame, font=ft, width=15, background="white")
            self.input.pack(side=TOP)
            self.btn_frame = frame(calc_frame)
            x, y = 0, 0
            for key in ("()%C", "+-*/", "1234", "5678", "90.="):
                for c in key:
                    if c == "=":
                        btn = button(self.btn_frame, c, self.equalAction)
                    elif c == "C":
                        btn = button(self.btn_frame, c, self.cleanAction)
                    else:
                        btn = button(self.btn_frame, c, lambda i=c: self.input.insert(INSERT, i))
                    btn.grid(row=x, column=y)
                    y += 1
                x += 1
                y = 0
            self.log = Text(r_frame, font=Font(family=('Verdana'), size=10), width=25, height=14, background="yellow")
            self.log.pack(side=RIGHT)
        def cleanAction(self):
            self.input.delete(0, END)
        def equalAction(self):
            tmp = self.input.get()
            try:
                result = tmp + "=" + str(eval(tmp))
                self.log.insert(1.0, result + "\n");
                print(result)
            except Exception:
                self.log.insert(1.0, "Wrong expression\n");
    if __name__ == '__main__':
        root = Tk()
        root.title("Calculator")
        root.geometry()
        app = App(root)
        root.mainloop()

1 个答案:

答案 0 :(得分:0)

您可以将功能绑定到BackSpace

中的__init__

仅当光标(焦点)位于Entry

self.input.bind_all('<BackSpace>', self.cleanInput)

或适用于所有情况

main.bind_all('<BackSpace>', self.cleanInput)

并且您可以删除EntryText

中的文字
def cleanInput(self, event):
    self.input.delete(0, END)
    self.log.delete(1.0, END)

BTW:与绑定其他键的方式相同 - 例如数字

else:
    btn = button(self.btn_frame, c, lambda i=c: self.input.insert(INSERT, i))
    main.bind_all(c, lambda event, i=c:self.input.insert(INSERT, i))

修改

完整的工作代码:

(问题:当光标位于Entry时,插入两次 - 正常且通过绑定)

# python 2.x
#from Tkinter import *
#from tkFont import Font

# python 3.x
from tkinter import * 
from tkinter.font import Font

class App:
    def __init__(self, tk):

        self.tk = tk
        self.tk.title("Calculator")
        #self.tk.geometry()

        self.button_font = Font(family=('Verdana'), size=14)        

        main_frame  = self.create_frame(self.tk)
        left_frame  = self.create_frame(main_frame)
        right_frame = self.create_frame(main_frame)
        calc_frame  = self.create_frame(left_frame)

        self.btnquit = self.create_button(calc_frame, "Quit", self.tk.destroy)
        self.btnquit.pack(side = LEFT)

        self.log = Text(right_frame, font=Font(family=('Verdana'), size=10), width=25, height=14, background="yellow")
        self.log.pack(side=RIGHT)

        self.input_text = StringVar()
        self.input = Entry(calc_frame, font=self.button_font, width=15, background="white", textvariable=self.input_text)
        self.input.pack(side=TOP)

        btn_frame = self.create_frame(calc_frame)

        for x, key in enumerate( ("()%C", "+-*/", "1234", "5678", "90.=") ):
            for y, c in enumerate(key):
                if c == "=":
                    btn = self.create_button(btn_frame, c, self.equalAction)
                elif c == "C":
                    btn = self.create_button(btn_frame, c, self.cleanAction)
                else:
                    btn = self.create_button(btn_frame, c, lambda number=c: self.insertNumber(number))
                    #main.bind_all(c, lambda event, number=c: self.insertNumber(number))
                btn.grid(row=x, column=y)

        self.btn_backspace = self.create_button(btn_frame, "<-", self.deleteLastDigit)
        self.btn_backspace.grid(row=5, column=2, columnspan=2, sticky="we")

        self.btn_loop = self.create_button(btn_frame, "LOOP", self.loopAction)
        self.btn_loop.grid(row=5, column=0, columnspan=2, sticky="we")

        main_frame.bind_all('<BackSpace>', self.cleanAction)
        main_frame.bind_all('<Escape>', self.deleteLastDigit)

    def loopAction(self): 
        bedmas = [ "()", "x^n", "*/", "+-" ]
        for element in bedmas:
            self.log.insert(INSERT,"\n"+element)

    # event=None to use function in command= and in binding
    def deleteLastDigit(self, event=None): 
        self.input_text.set( self.input_text.get()[:-1] )


    def insertNumber(self, number):
        self.input_text.set( self.input_text.get() + number )

    def cleanAction(self):
        self.input_text.set("")
        self.log.delete(1.0, END)

    def equalAction(self):
        tmp = self.input_text.get()
        try:
            result = tmp + "=" + str(eval(tmp))
            self.log.insert(1.0, result + "\n");
            print(result)
        except Exception:
            self.log.insert(1.0, "Wrong expression\n");

    def create_button(self, frame, text, command=None):
        return Button(frame, text=text, font=self.button_font, width=3, command=command)

    def create_frame(self, frame, side=LEFT, bg="black"):
        f = Frame(frame, background=bg, padx=5, pady=5)
        f.pack(side=side, expand=YES, fill=BOTH)
        return f

    def run(self):
        self.tk.mainloop()

#---------------------------------------------------------------------

if __name__ == '__main__':
    App(Tk()).run()