python用gui做一个猜数字小游戏
时间: 2023-10-08 21:04:36 浏览: 122
好的,我们可以使用Python自带的GUI库Tkinter来实现这个猜数字小游戏。
首先,我们需要导入Tkinter库和random库:
```python
import tkinter as tk
import random
```
然后,我们需要定义一个函数来生成随机数,并将它存储在一个变量中:
```python
def generate_number():
global number
number = random.randint(1, 100)
```
接下来,我们需要定义一个函数来处理用户输入的数字,并根据用户猜测的数字给出不同的提示:
```python
def check_guess():
guess = int(guess_box.get())
if guess < number:
result_label.config(text="猜小了!")
elif guess > number:
result_label.config(text="猜大了!")
else:
result_label.config(text="恭喜你,猜对了!")
```
在主函数中,我们需要创建一个窗口,并添加一些控件,如标签、输入框、按钮等:
```python
window = tk.Tk()
window.title("猜数字游戏")
start_button = tk.Button(window, text="开始游戏", command=generate_number)
start_button.pack()
guess_box = tk.Entry(window)
guess_box.pack()
guess_button = tk.Button(window, text="猜数字", command=check_guess)
guess_button.pack()
result_label = tk.Label(window, text="")
result_label.pack()
window.mainloop()
```
完整代码如下:
```python
import tkinter as tk
import random
def generate_number():
global number
number = random.randint(1, 100)
def check_guess():
guess = int(guess_box.get())
if guess < number:
result_label.config(text="猜小了!")
elif guess > number:
result_label.config(text="猜大了!")
else:
result_label.config(text="恭喜你,猜对了!")
window = tk.Tk()
window.title("猜数字游戏")
start_button = tk.Button(window, text="开始游戏", command=generate_number)
start_button.pack()
guess_box = tk.Entry(window)
guess_box.pack()
guess_button = tk.Button(window, text="猜数字", command=check_guess)
guess_button.pack()
result_label = tk.Label(window, text="")
result_label.pack()
window.mainloop()
```
运行程序,你就可以在窗口中玩猜数字小游戏了。
阅读全文