【问题标题】:Adding a backspace button to a Python GUI Calculator将退格按钮添加到 Python GUI 计算器
【发布时间】:2013-12-19 09:10:26
【问题描述】:

我正在使用 tkinter 在 python 中制作一个 GUI 计算器。计算器工作得很好,现在我想添加一个退格功能,以便清除显示屏上的最后一个数字。例如 321 将变为 32。我尝试定义函数“退格”和“bind_all”方法,但我不太确定它们是如何工作的,从而导致错误消息。如果有人能告诉我如何处理并解释它,将不胜感激。

非常感谢任何帮助。

from tkinter import *

def quit ():
root.destroy()
# the main class
class Calc():
def __init__(self):
    self.total = 0
    self.current = ""
    self.new_num = True
    self.op_pending = False
    self.op = ""
    self.eq = False

#setting the variable when the number is pressed
def num_press(self, num):
    self.eq = False
    temp = text_box.get()
    temp2 = str(num)
    if self.new_num:
        self.current = temp2
        self.new_num = False

    else:
        if temp2 == '.':
            if temp2 in temp:
                return
        self.current = temp + temp2
    self.display(self.current)



# event=None to use function in command= and in binding
def clearLastDigit(self, event=None):
    current = self.text_box.get()[:-1]
    self.text_box.delete(0, END)
    self.text_box.current(INSERT, text)


def calc_total(self):
    self.eq = True
    self.current = float(self.current)
    if self.op_pending == True:
        self.do_sum()
    else:
        self.total = float(text_box.get())

#setting up the text display area
def display(self, value):
    text_box.delete(0, END)
    text_box.insert(0, value)


#Opperations Button
def do_sum(self):
    if self.op == "add":
        self.total += self.current
    if self.op == "minus":
        self.total -= self.current
    if self.op == "times":
        self.total *= self.current
    if self.op == "divide":
        self.total /= self.current
    self.new_num = True
    self.op_pending = False
    self.display(self.total)

def operation(self, op):
    self.current = float(self.current)
    if self.op_pending:
        self.do_sum()
    elif not self.eq:
        self.total = self.current
    self.new_num = True
    self.op_pending = True
    self.op = op
    self.eq = False

#Clear last entry
def cancel(self):
    self.eq = False
    self.current = "0"
    self.display(0)
    self.new_num = True

#Clear all entries
def all_cancel(self):
    self.cancel()
    self.total = 0

#backspace button
def backspace(self):
    self.cancel()
    self.display(len(self.text_box.get())-1)


#Changing the Sign (+/-)
def sign(self):
    self.eq = False
    self.current = -(float(text_box.get()))
    self.display(self.current)



#Global Varibles that are used within Attributes
sum1 = Calc()
root = Tk()
calc = Frame(root)
calc.grid()

#Creating the window for the calculator
root.title("Calculator")
text_box = Entry(calc, justify=RIGHT)
text_box.grid(row = 0, column = 0, columnspan = 3, pady = 5)
text_box.insert(0, "0")

#buttons 1-9 (Displayed row by row)
numbers = "789456123"
i = 0
bttn = []
for j in range(1,4):
for k in range(3):
    bttn.append(Button(calc, text = numbers[i], width= 5, height = 2, bg="#fe0000"))
    bttn[i].grid(row = j, column = k)
    bttn[i]["command"] = lambda x = numbers[i]: sum1.num_press(x)
    i += 1
#button 0
bttn_0 = Button(calc, text = "0", width= 5, height = 2, bg="#fe0000")
bttn_0["command"] = lambda: sum1.num_press(0)
bttn_0.grid(row = 4, column = 1, pady = 5)

#button / (Divide)
bttn_div = Button(calc, text = chr(247), width= 5, height = 2, bg="#00b0f0" )
bttn_div["command"] = lambda: sum1.operation("divide")
bttn_div.grid(row = 1, column = 3, pady = 5)

#button x (Times)
bttn_mult = Button(calc, text = "x", width= 5, height = 2, bg="#00b0f0")
bttn_mult["command"] = lambda: sum1.operation("times")
bttn_mult.grid(row = 2, column = 3, pady = 5)

#button - (Minus)
minus = Button(calc, text = "-", width= 5, height = 2, bg="#00b0f0")
minus["command"] = lambda: sum1.operation("minus")
minus.grid(row = 4, column = 3, pady = 5)

#button + (Plus)
add = Button(calc, text = "+", width= 5, height = 2, bg="#00b0f0")
add["command"] = lambda: sum1.operation("add")
add.grid(row = 3, column = 3, pady = 5)

#button + or - (Plus/minus)
neg= Button(calc, text = "+/-", width= 5, height = 2, bg="#7030a0")
neg["command"] = sum1.sign
neg.grid(row = 5, column = 0, pady = 5)

#button Clear (Clear)
clear = Button(calc, text = "C", width= 5, height = 2, bg="yellow")
clear["command"] = sum1.cancel
clear.grid(row = 5, column = 1, pady = 5)

#button All Clear ( All Clear)
all_clear = Button(calc, text = "CE", width= 5, height = 2, bg="yellow")
all_clear["command"] = sum1.all_cancel
all_clear.grid(row = 5, column = 2, pady = 5)

#button . (Decimal)
point = Button(calc, text = ".", width= 5, height = 2, bg="#c00000")
point["command"] = lambda: sum1.num_press(".")
point.grid(row = 4, column = 0, pady = 5)

#button = (Equals)
equals = Button(calc, text = "=", width= 5, height = 2, bg="#7030a0")
equals["command"] = sum1.calc_total
equals.grid(row = 4, column = 2, pady = 5)

#button Quit
quit_bttn = Button(calc, text ="Quit", width=5, height = 2, bg="green")
quit_bttn["command"] = quit
quit_bttn.grid(row = 5, column = 3)

#button BackSpace
backspace_bttn = Button(calc, text = "Backspace", width= 15, height = 2, bg="yellow")
backspace_bttn["command"] = sum1.backspace
backspace_bttn.grid(row = 6, column = 0, columnspan = 4)


root.mainloop()

【问题讨论】:

  • @furas 这是我收到的错误line 106, in backspace self.display(len(self.text_box.get())-1) AttributeError: 'Calc' object has no attribute 'text_box'
  • 在原始版本中(请参阅我的答案中的链接)所有按钮都在课堂内,并且有 self.text_box 但你有所有的课外所以你有 text_box 而不是 self.text_box
  • 如果你在类之外有代码,你应该放弃使用类并将所有函数(经过一些修改)从类移到外面。有人可能会问“为什么你把一些函数放在类里面,而把另一些放在外面?你真的知道如何使用类吗?”

标签: python tkinter calculator


【解决方案1】:

显示错误消息 - 可能你的参数数量有问题。 bind_all 用两个参数调用函数 backspace(self, event), command 只用一个参数调用函数 backspace(self)

def clearLastDigit(self, event=None):之前的代码中查看我的评论

# event=None to use function in command= and in binding

要将backspacecommand= 一起使用,您需要

def backspace(self):
    self.cancel()
    self.display(len(self.text_box.get())-1)

要将backspacebind_all 一起使用,您需要

def backspace(self, event):
    self.cancel()
    self.display(len(self.text_box.get())-1)

顺便说一句:

len(self.text_box.get())-1 给你文本长度减 1。如果你需要排序文本 (321 -> 32) 使用 self.display( self.text_box.get()[:-1] )


回复How do I backspace and clear the last equation and also a quit button?查看带退格键的计算器


编辑:对于command,您只需将backspace(self) 更改为此

def backspace(self):
    text = text_box.get()[:-1]
    if text == "":
        text = "0"
    self.current = text
    self.display( text )

在某些特殊情况下,可能需要进行一些其他更改才能获得正确的结果。

【讨论】:

  • 感谢您的回复。所以如果我要使用命令方法,我会怎么做。
  • 对于命令,您需要更改backspace(),请参阅答案中的新代码。
  • 非常感谢!代码现在工作正常。你提到了一些关于修复课程的事情,你能解释一下我可以做些什么来改进它。谢谢
  • 老师可以问“为什么只放部分代码在课堂上?为什么不把所有代码都放在课堂上?”最好的解决方案是将所有内容放在类中 - 请参阅我对How do I backspace and clear the last equation and also a quit button? 的回答中的示例 - 所有代码都在类中,除了我创建类实例并使用run() 启动mainloop 的最后一行。
  • 那么要将所有内容放在同一个类中,是否会从#Global Varibles that are used within Attributes 开始缩进所有内容?
猜你喜欢
  • 1970-01-01
  • 2021-08-08
  • 1970-01-01
  • 2012-11-14
  • 1970-01-01
  • 1970-01-01
  • 2014-05-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多