计算器1

发布时间 2023-09-07 09:17:57作者: 沈Q

利用python tinker来写交互界面

 

主要代码由两部分组成,一方面是交互页面的按钮,另一个是按钮与功能的绑定。
首先创建一个交互窗口
from tkinter import*
window=Tk()
window.title("计算器")
window.geometry("400x500+100+200") //初始窗口位置及大小
window.resizable(0,0) //窗口不可改变大小
window.config(bg='gray')窗口背景色
window.mainloop()
然后创建各种交互按钮
button(i)for i in['AC','(',')','%'],
button(i)for i in'123+',
button(i)for i in'456-',
button(i)for i in'789x',
button(i)for i in'0./=',
最后是交互按钮与算法的绑定

 

 

def calc_sqrt():
content = text_area.get()
if len(content) > 0:
result = eval(content)
text_area.set(math.sqrt(result))


for i in range(4):
for j in range(3):
button = tk.Button(frame_low_left, text=str(ls[i][j]), width=5, font=font_16, relief=tk.RAISED)
button.grid(row=i, column=j, padx=12, pady=12)
if i == 3 and j == 2:
button.config(command=calc_sqrt)
else:
button.config(command=get_fun(set_content, ls[i][j]))

 

def clear(area):
area.set('')


def calc():
content = text_area.get()
if len(content) > 0:
content = eval(str(text_area.get()))
text_area.set(content)


for i in range(2):
button = tk.Button(frame_upper_sec, text=sec[i], width=8, font=font_16, relief=tk.RAISED,
bg=('pink' if i == 0 else 'yellow'))
button.grid(row=0, column=i, padx=26, pady=4)
if i == 0:
button.config(command=lambda: clear(text_area))
else:
button.config(command=calc)

text_area.set('')