学Python没几天,闲时自己编写的猜数字小游戏
代码:
import tkinter as tk
from tkinter import messagebox
import random
def guess_number():
number = random.randint(1, 100)
def check_number():
guess = int(entry.get())
if guess < number:
result_label.config(text="猜小了,再试一次!")
entry.delete(0, 'end')# 清空输入框
elif guess > number:
result_label.config(text="猜大了,再试一次!")
entry.delete(0, 'end')# 清空输入框
else:
result_label.config(text="恭喜你,猜对了!")
if messagebox.askyesno("提示", "要再玩一次吗?"):
new_number()
else:
root.destroy()
def new_number():
nonlocal number
number = random.randint(1, 100)
result_label.config(text="")
entry.delete(0, 'end')
root = tk.Tk()
root.title("猜数字游戏")
# 设置对话框的大小
root.geometry("1000x375")# 宽1000,高375
# 指定字体大小
font_size = 20
label = tk.Label(root, text="我已经想好了一个1到100之间的整数,请猜猜是多少:", font=('Arial', font_size))
label.pack(pady=35)# 增加上下间距
entry = tk.Entry(root, width=10, font=('Arial', font_size))# 增加输入框的宽度和字体大小
entry.pack(pady=25)
entry.bind('<Return>', lambda event=None: check_number())# 绑定回车键确认
check_button = tk.Button(root, text="确认", command=check_number, font=('Arial', font_size))# 按钮字体大小
check_button.pack(pady=25)
result_label = tk.Label(root, text="", font=('Arial', font_size))# 结果文本的字体大小
result_label.pack(pady=20)
root.mainloop()
guess_number()
guess_number()这个函数,可以定义成一个'类',代码看上去会更加'优雅'~~~ 不错,学习了 @Project :pythonproject
@file :猜数字游戏.py
@IDE :PyCharm
@AuThor:海绵的烂笔头
@date :2023-07-14 15:06
'''
import random
number = random.randint(1, 100)
guess = 0
tries = 0
print("猜猜看我心里想的是哪个数字!")
while guess != number:
guess = int(input("请输入一个数字:"))
tries += 1
if guess > number:
print("太大了!")
elif guess < number:
print("太小了!")
else:
print("恭喜你猜对了!你用了", tries, "次猜中了数字", number)
本帖最后由 白水饮 于 2024-8-23 17:46 编辑
在 check_number 方法中,要添加异常处理来确保用户输入的是有效整数,不然报错
haimiandashu 发表于 2024-8-23 17:38
@Project :pythonproject
@file :猜数字游戏.py
@IDE :PyCharm
输个字母就报错了,做个处理就好,其他完美 感谢分享! anning666 发表于 2024-8-23 16:37
guess_number()这个函数,可以定义成一个'类',代码看上去会更加'优雅'~~~
窗口显示跟布局,最后的再来一次,跟确定,不想再次弹窗,直接在游戏界面显示,总弄不好 能指点下么?
import tkinter as tk
from tkinter import Toplevel, Frame, Label, Button, Entry, messagebox
import random
def on_enter(event=None):
"""当按下回车键时触发猜数字操作"""
guess_number()
def guess_number():
global error_count, secret_number
try:
number = int(entry.get())
if number == secret_number:
show_result_popup(error_count)
error_count = 0
else:
if number < secret_number:
result_text = "太小了,再试一次!"
else:
result_text = "太大了,再试一次!"
label_result.config(text=result_text, fg="red", font=("Arial", 14, "bold"), wraplength=200)
error_count += 1
except ValueError:
label_result.config(text="无效的输入,请输入一个数字!", fg="red", font=("Arial", 14, "bold"), wraplength=200)
error_count += 1
entry.delete(0, tk.END)
def show_result_popup(tries):
"""显示结果的弹出窗口"""
global popup
popup = Toplevel(root)
popup.title("游戏结果")
# 弹出窗口大小和位置
popup_width = 300
popup_height = 200
x = root.winfo_x() + (root.winfo_width() - popup_width) // 2
y = root.winfo_y() + (root.winfo_height() - popup_height) // 2
popup.geometry(f"{popup_width}x{popup_height}+{x}+{y}")
# 创建消息标签
label_message = Label(popup, text=f"你答对了!你共计花费了 {tries} 次答对。", font=("Arial", 14, "bold"),
wraplength=260)
label_message.pack(pady=20)
# 创建按钮的容器Frame
button_frame = Frame(popup)
button_frame.pack(side=tk.BOTTOM, pady=20, padx=20, fill=tk.X)
# 创建"再来一次"按钮
btn_again = Button(button_frame, text="再来一次", command=popup.destroy_and_reset)
btn_again.pack(side=tk.LEFT, padx=10, pady=10)
# 创建"确定"按钮
btn_ok = Button(button_frame, text="确定", command=popup.destroy)
btn_ok.pack(side=tk.RIGHT, padx=10, pady=10)
def destroy_and_reset():
"""销毁弹出窗口并重置游戏"""
global secret_number, error_count
secret_number = random.randint(1, 100)
error_count = 0
entry.delete(0, tk.END)# 清空输入框
label_result.config(text="")
# 初始化设置
root = tk.Tk()
root.title("猜数字游戏")
root.geometry("300x200")
# 随机生成一个数字
secret_number = random.randint(1, 100)
error_count = 0
# 创建提示标签
label_instruction = Label(root, text="请在1-100中选择一个数字", font=("Arial", 14), wraplength=280)
label_instruction.pack()
# 创建输入框
entry = Entry(root, font=("Arial", 14))
entry.pack()
entry.bind('<Return>', on_enter)
# 创建显示结果的标签
label_result = Label(root, text="", fg="black", font=("Arial", 14), wraplength=280)
label_result.pack()
# 创建猜数字按钮
guess_button = Button(root, text="猜数字", command=guess_number)
guess_button.pack()
root.mainloop() 哈哈,不错 小白学习一下