import tkinter as tk
input_text="" def button_click(char): """tr""" global input_text
if char=='=':
result=round(eval(input_text),2)
show_lable.config(text=res(result))
input_text=srt(result)
elif char == "←":
input_text=""
show_label.config(text="0")
else:
input_text+=char
show_label.config(text=input_text)
root = tk.Tk() root.title(“计算器”) root.geometry(“320x400”) # 小巧的窗口 root.resizable(False, False) # 固定大小,避免乱拖
show_label = tk.Label(
root,
text=“0”,
font=(“楷体”, 30), #字体
bg=“#f8f8f8”,
anchor=“e”, # 文字右对齐
padx=10
)
show_label.pack(fill=“both”, expand=True, pady=10)
buttons = [
‘7’, ‘8’, ‘9’, ’+’,
‘4’, ‘5’, ‘6’, ’-’,
‘1’, ‘2’, ‘3’, ’×’,
’←’, ‘0’, ’=’, ’÷’
]
btn_frame = tk.Frame(root)
btn_frame.pack(fill=“both”, expand=True, padx=10, pady=10)
for idx,char in enumerate(buttons):
if char ==‘x’:
real_char= ’*’
elif char==’÷’:
real_char= ’/’
else:
real_char=char
btn=tk.Button(
btn_frame,
text=char,
font=(“微软雅黑”,20),
)
btn.grid(
row=idx//4,
column=idx%4,
sticky=“nsew”,
)
for i in range(4):
btn_frame.grid_columconfigure(i,weight=1)
for i in range(4):
btn_frame.grid_rowconfigure(i,weight=1)
root.mainloop()