Have you ever wondered if you could develop a desktop gadget? If the answer is "yes", then you have come to the right place! Today, we're going to use the tkinter library in Python to create a simple desktop calculator.
1. Why tkinter?
tkinter is Python's standard GUI library. It's very friendly for beginners as it offers a large number of pre-made parts such as buttons, text boxes, etc., which makes developing graphical user interfaces incredibly easy.
2. Start our calculator journey
First, introduce the necessary libraries:
import tkinter as tk
from tkinter import ttk
Then, we create a class called SimpleCalculator, which inherits from tk. Tk。
class SimpleCalculator(tk.Tk):
def __init__(self):
super().__init__()
self.title("简易计算器") # 设置窗口标题
self.geometry("300x250") # 设置窗口大小
Now let's add a method create_widgets to this class for adding and laying out the interface widgets:
def create_widgets(self):
# 创建一个文本框,用于显示和输入数据
self.entry = ttk.Entry(self, width=30)
self.entry.grid(row=0, column=0, columnspan=4, pady=20) # 定位文本框的位置
self.create_buttons() # 创建按钮
Here's how we create a button. We define a list of the text of each button and its row and column positions in the grid layout:
def create_buttons(self):
# 按钮及其位置的列表
buttons = [
("7", 1, 0),
("8", 1, 1),
("9", 1, 2),
("+", 1, 3),
...
]
for (text, row, col) in buttons:
self.create_button(text, row, col) # 创建每一个按钮
For each button, we'll create it using create_button method and bind an event to it:
def create_button(self, text, row, col):
# 创建按钮,并绑定button_click事件
button = ttk.Button(self, text=text, width=7, command=lambda: self.button_click(text))
button.grid(row=row, column=col, padx=5, pady=5) # 定位按钮位置
When the user clicks the button, button_click method is triggered:
def button_click(self, char):
current = self.entry.get() # 获取文本框当前的内容
if char == "=":
# 尝试计算表达式的结果
try:
result = eval(current)
self.entry.delete(0, tk.END) # 清空文本框
self.entry.insert(0, str(result)) # 插入结果
except:
self.entry.delete(0, tk.END) # 清空文本框
self.entry.insert(0, "错误") # 显示错误信息
elif char == "C":
self.entry.delete(0, tk.END) # 清空文本框
else:
self.entry.insert(tk.END, char) # 向文本框插入字符
Finally, to start the calculator application, we create an instance of SimpleCalculator and start tkinter's event loop:
if __name__ == "__main__":
app = SimpleCalculator()
app.mainloop()
3. Demo video + complete code
The demo video is below, due to space limitations, if you need the full code, get the address for free: https://mp.weixin.qq.com/s/_GffebF6RFddxBbaZlwfsw
epilogue
That's our easy calculator! Although it seems simple, it's a great place to start for beginners. You can add more features to this, such as support for more math operations, history, or skin switching. If you're interested in programming, I encourage you to keep exploring. Python and tkinter give you powerful tools and endless possibilities. Don't stop, keep exploring, learning and creating!