import tkinter as tk
import keyboard
import random
import sys
def move_label(event):
global label_b
if event.name == ‘w’:
label.place(y=label.winfo_y() - 10)
root.update() # 每次移动后更新布局,确保位置信息准确
elif event.name == ‘a’:
label.place(x=label.winfo_x() - 10)
root.update()
elif event.name == ‘d’:
label.place(x=label.winfo_x() + 10)
root.update()
elif event.name == ‘s’:
label.place(y=label.winfo_y() + 10)
root.update()
# 判断两个标签是否碰撞
if is_collision(label, label_b):
print("结束")
ask_to_continue() # 结束程序,关闭窗口
else:
print("继续")
def is_collision(label1, label2):
root.update() # 强制更新窗口布局,确保能获取到正确的place_info
# 获取标签1的坐标和尺寸信息
x1 = int(label1.place_info()['x'])
y1 = int(label1.place_info()['y'])
width1 = label1.winfo_reqwidth()
height1 = label1.winfo_reqheight()
# 获取标签2的坐标和尺寸信息
x2 = int(label2.place_info()['x'])
y2 = int(label2.place_info()['y'])
width2 = label2.winfo_reqwidth()
height2 = label2.winfo_reqheight()
# 碰撞判断条件,考虑两个矩形是否有重叠部分
if (x1 < x2 + width2 and x1 + width1 > x2 and
y1 < y2 + height2 and y1 + height1 > y2):
return True
return False
def ask_to_continue():
global label_b
response = input("是否继续游戏?(y/n) ")
if response.lower() == ‘y’:
# 重置标签b的随机位置
window_width = root.winfo_width()
window_height = root.winfo_height()
random_x = random.randint(0, 600 - label_b.winfo_reqwidth())
random_y = random.randint(0, 400 - label_b.winfo_reqheight())
label_b.place(x=random_x, y=random_y)
root.update() # 更新窗口布局,确保新位置生效
elif response.lower() == 'n':
root.destroy() # 结束程序,关闭窗口
sys.exit()
else:
print("无效输入,请重新输入。")
ask_to_continue()
root = tk.Tk()
root.geometry(“600x400”)
创建绿色标签(字符串标签a)
label = tk.Label(root, text=“a”, bg=“green”, fg=“white”)
label.pack()
创建另一个字符串标签b,并设置随机位置
label_b = tk.Label(root, text=“b”, bg=“red”, fg=“white”)
root.update_idletasks() # 确保窗口大小已确定,以便获取正确的窗口尺寸信息
获取窗口的宽度和高度(此处已设置固定大小,可注释掉这部分代码,因为不再需要动态获取)
window_width = root.winfo_width()
window_height = root.winfo_height()
生成随机位置坐标,确保标签b在窗口内
random_x = random.randint(0, 600 - label_b.winfo_reqwidth())
random_y = random.randint(0, 400 - label_b.winfo_reqheight())
label_b.place(x=random_x, y=random_y)
root.update() # 再次更新,确保place_info可用
绑定键盘事件
keyboard.on_press(move_label)
root.mainloop()
标签:winfo,游戏,python,random,碰撞,update,label,place,root From: https://blog.csdn.net/qq_32257509/article/details/144120954