Python生成四则运算题目的带界面的代码
时间: 2024-09-20 11:17:25 浏览: 53
在Python中,你可以使用Tkinter库创建一个简单的图形用户界面(GUI),配合random模块来生成四则运算题目。下面是一个基本的示例,展示如何实现这个功能:
```python
import tkinter as tk
from random import randint
def generate_question():
num1 = randint(0, 10)
num2 = randint(0, 10)
operator = ['+', '-', '*', '/']
operator_choice = operator[randint(0, len(operator) - 1)]
if operator_choice == '+':
question = f"{num1} + {num2}"
elif operator_choice == '- {num2}"
elif operator_choice == '*':
question = f"{num1} * {num2}"
else:
# 避免除数为零的情况
while num2 == 0:
num2 = randint(1, 10)
question = f"{num1} / {num2}"
answer_label.config(text=question)
root = tk.Tk()
root.title("四则运算练习")
question_label = tk.Label(root, text="题目:")
question_label.pack()
answer_label = tk.Label(root, text="")
answer_label.pack()
generate_button = tk.Button(root, text="生成", command=generate_question)
generate_button.pack()
root.mainloop()
```
这个程序创建了一个窗口,包含两个标签:一个是显示题目,另一个是空的用于显示答案。点击“生成”按钮会随机选择两个数字和一个运算符,并更新题目内容。
阅读全文