向Python GUI计算器添加退格按钮
我正在用tkinter用python制作一个GUI计算器。计算器工作得非常好,现在我想添加一个退格函数,以便它清除显示器上的最后一个数字。例如,321将变成32。我已经尝试过定义函数“backspace”和“bind_all”方法,但我不太确定它们是如何工作的,从而导致错误消息。如果有人能告诉我怎么做并解释一下,我将不胜感激 非常感谢您的帮助向Python GUI计算器添加退格按钮,python,tkinter,calculator,Python,Tkinter,Calculator,我正在用tkinter用python制作一个GUI计算器。计算器工作得非常好,现在我想添加一个退格函数,以便它清除显示器上的最后一个数字。例如,321将变成32。我已经尝试过定义函数“backspace”和“bind_all”方法,但我不太确定它们是如何工作的,从而导致错误消息。如果有人能告诉我怎么做并解释一下,我将不胜感激 非常感谢您的帮助 from tkinter import * def quit (): root.destroy() # the main class class Cal
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()
显示错误消息-可能您的参数数量有问题
bind_all
用两个参数调用函数backspace(self,event)
,command
只用一个参数调用函数backspace(self)
请在def clearLastDigit(self,event=None)之前的代码中查看我的注释:
要使用backspace
和command=
您需要
def backspace(self):
self.cancel()
self.display(len(self.text_box.get())-1)
def backspace(self, event):
self.cancel()
self.display(len(self.text_box.get())-1)
要使用backspace
和bind\u all
您需要的
def backspace(self):
self.cancel()
self.display(len(self.text_box.get())-1)
def backspace(self, event):
self.cancel()
self.display(len(self.text_box.get())-1)
顺便说一下:
len(self.text\u box.get())-1
为文本长度减去1。如果需要分类器文本(321->32),请使用self.display(self.text\u box.get()[:-1])
请参见答案中带退格的计算器
编辑:对于
命令
您只需更改退格(self)
def backspace(self):
text = text_box.get()[:-1]
if text == "":
text = "0"
self.current = text
self.display( text )
在某些特殊情况下,可能需要进行一些其他更改才能获得正确的结果。@furas这是我在backspace self.display(len(self.text\u box.get())-1)AttributeError:Calc对象在oryginal版本中没有属性“text\u box”(请参阅我答案中的链接)所有按钮都在类内,有
self.text\u box
,但所有按钮都在类外,所以你有text\u box
,而不是self.text\u box
如果你有类外的代码,你应该放弃使用类,并将所有函数(经过一些修改)从类移到类外。有人可能会问:“为什么你把一些函数放在类内而把其他函数放在类外?你真的知道如何使用类吗?”谢谢你的回答。因此,如果我要使用命令方法,我将如何操作。对于命令,您需要更改backspace()
请参阅答案中的新代码。非常感谢!代码现在运行良好。你提到了一些关于修课的事情,你能解释一下我能做些什么来提高它吗。ThanksTeacher可以问“为什么你只把部分代码放在类中?为什么你不把所有代码都放在类中?”最好的解决方案是把所有代码都放在类中-参见我的答案中的示例-所有代码都在类中,除了我创建类实例的最后一行,我使用run()
启动mainloop
。因此,要把所有代码都放在同一个类中,是否将属性中使用的所有全局变量缩进到下?