如何在tkinter中让两个数字进行加减乘除
时间: 2024-02-13 13:06:37 浏览: 96
在 Tkinter 中创建一个简单的 GUI 计算器,让用户输入两个数字,选择运算符然后计算结果。以下是一个示例代码:
```python
import tkinter as tk
def calculate():
num1 = float(entry_num1.get())
num2 = float(entry_num2.get())
operator = operator_var.get()
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
result = num1 / num2
result_label.config(text="Result: " + str(result))
root = tk.Tk()
root.title("Calculator")
# create input fields
entry_num1 = tk.Entry(root)
entry_num1.pack()
entry_num2 = tk.Entry(root)
entry_num2.pack()
# create operator radio buttons
operator_var = tk.StringVar()
addition_radio = tk.Radiobutton(root, text="+", variable=operator_var, value='+')
addition_radio.pack()
subtraction_radio = tk.Radiobutton(root, text="-", variable=operator_var, value='-')
subtraction_radio.pack()
multiplication_radio = tk.Radiobutton(root, text="*", variable=operator_var, value='*')
multiplication_radio.pack()
division_radio = tk.Radiobutton(root, text="/", variable=operator_var, value='/')
division_radio.pack()
# create calculate button
calculate_button = tk.Button(root, text="Calculate", command=calculate)
calculate_button.pack()
# create result label
result_label = tk.Label(root, text="Result: ")
result_label.pack()
root.mainloop()
```
该代码创建了一个简单的 GUI 计算器,包括两个数字输入框、四个运算符单选按钮、一个计算按钮和一个结果标签。当用户单击“Calculate”按钮时,程序将从输入框中获取数字和运算符,并执行相应的计算。计算结果将显示在标签中。
阅读全文