使用tkinter设计简单计算器
时间: 2023-11-20 22:13:41 浏览: 82
好的,我可以为您提供一个基于tkinter的简单计算器的代码。请注意,这个计算器只支持加、减、乘、除四种基本运算。
```
from tkinter import *
class Calculator:
def __init__(self, master):
self.master = master
master.title("Calculator")
self.screen = Text(master, state='disabled', width=30, height=3, background="yellow", foreground="blue")
self.screen.grid(row=0, column=0, columnspan=4, padx=5, pady=5)
self.screen.configure(state='normal')
self.equation = ''
# create buttons
b1 = self.create_button(7)
b2 = self.create_button(8)
b3 = self.create_button(9)
b4 = self.create_button(u"\u232B", None)
b5 = self.create_button(4)
b6 = self.create_button(5)
b7 = self.create_button(6)
b8 = self.create_button(u"\u00F7")
b9 = self.create_button(1)
b10 = self.create_button(2)
b11 = self.create_button(3)
b12 = self.create_button('*')
b13 = self.create_button('.')
b14 = self.create_button(0)
b15 = self.create_button('+')
b16 = self.create_button('-')
b17 = self.create_button('=', None, 34)
buttons = [b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17]
# add buttons to the grid
count = 0
for row in range(1, 5):
for col in range(4):
buttons[count].grid(row=row, column=col)
count += 1
buttons[16].grid(row=5, column=0, columnspan=4)
def create_button(self, val, write=True, width=7):
return Button(self.master, text=val, command=lambda: self.click(val, write), width=width)
def click(self, text, write):
# add text to the equation
self.equation += str(text)
# update the equation in the screen
self.update_screen()
def update_screen(self):
# clear the screen
self.screen.configure(state='normal')
self.screen.delete('1.0', END)
# write the equation to the screen
self.screen.insert('1.0', self.equation)
self.screen.configure(state='disabled')
def evaluate(self):
try:
self.equation = str(eval(self.equation))
self.update_screen()
except:
self.equation = "Error"
self.update_screen()
def clear(self):
self.equation = ""
self.update_screen()
root = Tk()
root.geometry("250x250")
calc = Calculator(root)
root.mainloop()
```
在这个代码中,我们使用了tkinter的Text控件来显示计算器上的文本。我们通过self.screen.grid方法将文本框放在了计算器的第一行,然后在create_button方法中创建了所有的按钮。每当用户点击一个按钮时,我们会在self.equation字符串上添加相应的字符,并更新屏幕上的文本。当用户点击“=”按钮时,我们会尝试使用eval函数计算self.equation字符串,并将结果显示在屏幕上。如果计算失败,我们会将“Error”字符串显示在屏幕上。
这只是一个简单的计算器,但它可以作为一个好的起点来学习tkinter。
阅读全文