```python
import tkinter as tk
def click(num):
global op
op = op + str(num)
iptext.set(op)
def evaluate():
global op
output = str(eval(op))
iptext.set(output)
def clearDisplay():
global op
op = ""
iptext.set(op)
创建主窗口
root = tk.Tk()
root.title("计算器")
root.geometry("350x280")
root.resizable(False, False)
创建标签框
frame = tk.LabelFrame(root, bg='yellow', width=350, height=50)
frame.pack()
创建标签
label = tk.Label(frame, text="1+1=2", height=3, width=50, bg='yellow')
label.pack()
创建单行文本框
contentEntry = tk.Entry(root, font=('large', 15, 'bold'), bd=10, justify="right", insertwidth=4, textvariable=iptext)
contentEntry.grid(columnspan=10)
创建按钮
buttons = [
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', '.', '=', '+',
'C'
]
for index, button_text in enumerate(buttons):
btn = tk.Button(root, text=button_text, width=4, command=lambda num=button_text: click(int(num)), bg='yellow')
btn.grid(row=index // 4, column=index % 4)
绑定计算功能
root.bind('=', evaluate)
root.bind('C', clearDisplay)
运行主循环
root.mainloop()
代码说明:
导入Tkinter库:
使用`import tkinter as tk`导入Tkinter库。
定义全局变量:
定义全局变量`op`用于存储当前输入的表达式,`iptext`用于存储显示框中的文本。
定义按钮功能:
定义`click`函数用于更新表达式,`evaluate`函数用于计算表达式并更新显示框,`clearDisplay`函数用于清空表达式和显示框。
创建主窗口:
使用`tk.Tk()`创建主窗口,并设置标题、大小和不可调整大小。
创建标签框和标签:
使用`tk.LabelFrame`和`tk.Label`创建标签框和标签,显示初始表达式。
创建单行文本框:
使用`tk.Entry`创建单行文本框,用于显示和输入表达式。
创建按钮:
创建按钮,每个按钮对应一个数字或运算符,并绑定点击事件到`click`函数。
绑定计算功能:
使用`root.bind`将等号`=`绑定到`evaluate`函数,将`C`绑定到`clearDisplay`函数。
运行主循环:
使用`root.mainloop()`运行主循环,启动计算器界面。
这个示例提供了一个简单的图形界面计算器,用户可以通过按钮输入表达式并进行计算。你可以根据需要进一步扩展和优化这个计算器。