[Python] 纯文本查看 复制代码
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()