import random import tkinter as tk class GuessingGame: def __init__(self, master): self.master = master master.title("猜数字游戏") self.number = random.randint(0, 100) self.count = 0 self.low = 0 self.high = 100 self.label = tk.Label(master, text="请输入0到100之间任意整数") self.label.pack() self.entry = tk.Entry(master) self.entry.pack() self.button = tk.Button(master, text="提交", command=self.guess_number) self.button.pack() def guess_number(self): guess = int(self.entry.get()) self.count += 1 if guess < self.number: self.low = max(self.low, guess ) self.label.config(text="猜少了,请输入%d到%d之间任意整数:" % (self.low, self.high)) elif guess > self.number: self.high = min(self.high, guess ) self.label.config(text="猜多了,请输入%d到%d之间任意整数:" % (self.low, self.high)) else: if self.count == 1: self.label.config(text="哇!一次答对,也太厉害了吧!") else: self.label.config(text="恭喜你答对了,总尝试次数%d" % self.count) self.entry.delete(0, 'end') self.button.config(state='disabled') self.entry.config(state='disabled') root = tk.Tk() game = GuessingGame(root) root.mainloop()修改该代码,使其“提交”和“结束”按钮位于输入框右侧,记得输入框居中
时间: 2024-01-16 09:03:09 浏览: 176
python 使用tkinter 实现一个猜数字游戏
5星 · 资源好评率100%
import random
import tkinter as tk
class GuessingGame:
def __init__(self, master):
self.master = master
master.title("猜数字游戏")
self.number = random.randint(0, 100)
self.count = 0
self.low = 0
self.high = 100
# 使用 Frame 将输入框和按钮组合在一起
self.input_frame = tk.Frame(master)
self.input_frame.pack(pady=10)
self.label = tk.Label(self.input_frame, text="请输入0到100之间任意整数:")
self.label.pack(side=tk.LEFT)
self.entry = tk.Entry(self.input_frame)
self.entry.pack(side=tk.LEFT, padx=5)
self.button = tk.Button(self.input_frame, text="提交", command=self.guess_number)
self.button.pack(side=tk.LEFT)
self.quit_button = tk.Button(master, text="结束", command=master.quit)
self.quit_button.pack(pady=10)
# 设置输入框居中
self.input_frame.bind("<Configure>", self.center_input)
def guess_number(self):
guess = int(self.entry.get())
self.count += 1
if guess < self.number:
self.low = max(self.low, guess)
self.label.config(text="猜少了,请输入%d到%d之间任意整数:" % (self.low, self.high))
elif guess > self.number:
self.high = min(self.high, guess)
self.label.config(text="猜多了,请输入%d到%d之间任意整数:" % (self.low, self.high))
else:
if self.count == 1:
self.label.config(text="哇!一次答对,也太厉害了吧!")
else:
self.label.config(text="恭喜你答对了,总尝试次数%d" % self.count)
self.entry.delete(0, 'end')
self.button.config(state='disabled')
self.entry.config(state='disabled')
def center_input(self, event):
"""使输入框居中"""
self.input_frame.place(relx=0.5, rely=0.5, anchor=tk.CENTER)
root = tk.Tk()
game = GuessingGame(root)
root.mainloop()
阅读全文