如何退格并清除最后一个等式以及退出按钮? [英] How do I backspace and clear the last equation and also a quit button?

查看:23
本文介绍了如何退格并清除最后一个等式以及退出按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过了:

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

之前 self.input = ...

before self.input = ...

但它的语法无效.退格键只有在数字前面时才有效,但我希望它能够对输入的最后一个数字进行空格键,清除最后一个等式,然后:

But it came out invalid syntax. And the backspace only works if its in front of the number but I want it to be able to ackspace the last number entered, clear the last equation and then:

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

推荐答案

您可以在 __init__

仅当光标(焦点)在Entry

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

或适用于所有情况

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

然后你可以删除 EntryText

and than you can delete text in Entry and Text

def cleanInput(self, event):
    self.input.delete(0, END)
    self.log.delete(1.0, END)

<小时>

顺便说一句:与绑定其他键的方式相同 - 例如数字


BTW: the same way you can bind other keys - for example digits

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 时,数字被插入两次 - 通常和绑定)

(issue: at that moment when cursor is in Entry numbers are inserted twice - normaly and by binding)

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

这篇关于如何退格并清除最后一个等式以及退出按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆