用tkinter库写一个计算器
时间: 2023-11-05 07:17:50 浏览: 97
使用tkinter库可以很方便地编写一个计算器。可以通过创建一个窗口,然后在窗口中添加各种按钮和文本框来实现计算器的功能。下面是一个简单的示例代码:
```python
import tkinter as tk
# 创建一个窗口
window = tk.Tk()
window.title("计算器")
# 创建一个用于显示结果的文本框
result_text = tk.StringVar()
result_text.set("0")
result_label = tk.Label(window, textvariable=result_text, width=25, height=2)
result_label.grid(row=0, column=0, columnspan=4)
# 定义操作函数
def button_click(number):
current = result_text.get()
if current == "0":
result_text.set(number)
else:
result_text.set(current + number)
def button_clear():
result_text.set("0")
def button_equal():
try:
result = eval(result_text.get())
result_text.set(str(result))
except:
result_text.set("Error")
# 创建数字和操作按钮
buttons = [
("7", 1, 0),
("8", 1, 1),
("9", 1, 2),
("/", 1, 3),
("4", 2, 0),
("5", 2, 1),
("6", 2, 2),
("*", 2, 3),
("1", 3, 0),
("2", 3, 1),
("3", 3, 2),
("-", 3, 3),
("0", 4, 0),
(".", 4, 1),
("=", 4, 2),
("+", 4, 3)
]
for button in buttons:
text, row, col = button
btn = tk.Button(window, text=text, width=5, height=2, command=lambda text=text: button_click(text))
btn.grid(row=row, column=col)
# 创建清零按钮
clear_btn = tk.Button(window, text="C", width=5, height=2, command=button_clear)
clear_btn.grid(row=5, column=0)
# 创建等号按钮
equal_btn = tk.Button(window, text="=", width=5, height=2, command=button_equal)
equal_btn.grid(row=5, column=1)
# 运行窗口
window.mainloop()
```
这个示例中创建了一个窗口,并在窗口中添加了一个用于显示结果的文本框和各种数字和操作按钮。每当按钮被点击时,对应的操作函数会被调用,然后更新结果的文本框。最后,通过调用`window.mainloop()`来运行窗口,使得窗口界面可以响应用户的操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [python的Tkinter库简单应用——开发一个简易计算器](https://blog.csdn.net/weixin_44120833/article/details/110467105)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [tkinter制作一个简单计算器](https://blog.csdn.net/guleilei0/article/details/129855066)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文