请你帮我用python和ttk来帮我实现一个好看的GUI计算器
时间: 2024-05-01 09:18:41 浏览: 142
带GUI的计算器--Java实现
5星 · 资源好评率100%
好的,这个问题很简单。以下是Python代码实现一个好看的GUI计算器:
```
from tkinter import *
from tkinter import ttk
class Calculator:
def __init__(self, master):
self.master = master
master.title("Calculator")
# create input field
self.input_field = ttk.Entry(master, width=40)
self.input_field.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
# create buttons
button_list = [
"7", "8", "9", "+",
"4", "5", "6", "-",
"1", "2", "3", "*",
"0", ".", "=", "/"
]
r = 1
c = 0
for b in button_list:
ttk.Button(master, text=b, command=lambda button=b: self.button_click(button)).grid(row=r, column=c, padx=5, pady=5)
c += 1
if c > 3:
c = 0
r += 1
def button_click(self, button):
current = self.input_field.get()
if button == "C":
self.input_field.delete(0, END)
elif button == "=":
try:
result = eval(current)
self.input_field.delete(0, END)
self.input_field.insert(0, result)
except:
self.input_field.delete(0, END)
self.input_field.insert(0, "Error!")
else:
self.input_field.insert(END, button)
root = Tk()
calc = Calculator(root)
root.mainloop()
```
以上代码创建了一个能实现加减乘除四则运算的GUI计算器,使用了Python的Tkinter库和ttk模块。您可以根据自己的喜好对GUI界面进行调整。
阅读全文