Python制作自动生成四则运算题目的带界面的代码
时间: 2024-09-20 08:17:20 浏览: 50
在Python中,我们可以使用tkinter库来创建一个简单的图形用户界面(GUI),然后结合随机数生成来实现四则运算题目生成器。下面是一个简化的示例代码:
```python
import tkinter as tk
from random import randint
def generate_question():
num1 = randint(0, 100)
num2 = randint(0, 100)
operator = ['+', '-', '*', '/']
operator_choice = operator[randint(0, len(operator) - 1)]
if operator_choice == '/':
while num2 == 0:
num2 = randint(1, 100)
question = f"{num1} {operator_choice} {num2}"
answer_entry.delete(0, tk.END)
answer_entry.insert(0, str(eval(question)))
root = tk.Tk()
root.title("四则运算题目生成器")
question_label = tk.Label(root, text="题目:")
question_label.grid(row=0, column=0)
num1_label = tk.Label(root, text=f"第1个数字:")
num1_label.grid(row=1, column=0)
num1_entry = tk.Entry(root)
num1_entry.grid(row=1, column=1)
num2_label = tk.Label(root, text=f"第2个数字:")
num2_label.grid(row=2, column=0)
num2_entry = tk.Entry(root)
num2_entry.grid(row=2, column=1)
operator_buttons = ["+", "-", "*", "/"]
for i, op in enumerate(operator_buttons):
button = tk.Button(root, text=op, command=lambda o=op: generate_question(o))
button.grid(row=3, column=i, padx=5)
answer_label = tk.Label(root, text="结果:")
answer_label.grid(row=4, column=0)
answer_entry = tk.Entry(root)
answer_entry.grid(row=4, column=1)
generate_button = tk.Button(root, text="生成", command=generate_question)
generate_button.grid(row=5, columnspan=2)
root.mainloop()
阅读全文