python计算器 tkinter
时间: 2023-09-08 12:08:43 浏览: 168
Python中的Tkinter库提供了创建图形用户界面(GUI)的工具。下面是一个示例代码,用于创建一个简单的计算器界面:
```python
from tkinter import *
def btn_click(btn_val):
current = display_entry.get()
new = current + btn_val
display_entry.delete(0, END)
display_entry.insert(0, new)
def calculate():
expression = display_entry.get()
try:
result = eval(expression)
display_entry.delete(0, END)
display_entry.insert(0, str(result))
except:
display_entry.delete(0, END)
display_entry.insert(0, "Error")
root = Tk()
root.title("Calculator")
display_entry = Entry(root, width=30)
display_entry.grid(row=0, column=0, columnspan=4)
buttons = [
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', '.', '=', '+'
]
row_index = 1
col_index = 0
for btn in buttons:
Button(root, text=btn, width=5, command=lambda x=btn: btn_click(x)).grid(row=row_index, column=col_index)
col_index += 1
if col_index > 3:
col_index = 0
row_index += 1
Button(root, text="C", width=5, command=lambda: display_entry.delete(0, END)).grid(row=row_index, column=col_index)
Button(root, text="=", width=5, command=calculate).grid(row=row_index+1, column=col_index)
root.mainloop()
```
这个示例利用Tkinter库创建了一个简单的计算器界面,包括数字按钮、运算符按钮和一个显示结果的文本框。用户可以通过点击按钮输入计算表达式,并按下"="按钮进行计算。
阅读全文
相关推荐
![py](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)