You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python Tkinter制作按钮追逐小游戏

要实现鼠标靠近按钮自动移位的效果,你可以在原有代码基础上增加鼠标移动事件监听、距离计算逻辑,同时修正原有代码的两个小问题:

  • btn1函数内的print语句没有缩进,会报语法错误
  • 不要同时调用pack和place两种布局方法,二者会冲突,保留place即可

以下是完整可运行的实现代码:

from tkinter import *
import random

# 创建主窗口
win = Tk()
win.geometry("600x400") # 固定窗口大小方便位置计算
RESPONSE_RADIUS = 50 # 设置响应半径,单位为像素

def btn1():
    print("I Don't Know Your Name")

# 检查鼠标位置,触发按钮移动
def check_mouse_pos(event):
    # 计算按钮中心坐标
    btn_center_x = button.winfo_x() + button.winfo_width()/2
    btn_center_y = button.winfo_y() + button.winfo_height()/2
    # 计算鼠标与按钮中心的欧氏距离
    distance = ((event.x - btn_center_x)**2 + (event.y - btn_center_y)**2)**0.5
    # 距离小于响应半径时随机移动按钮
    if distance < RESPONSE_RADIUS:
        # 随机生成新位置,限制在窗口10%-90%区域避免按钮跑出视野
        new_relx = random.uniform(0.1, 0.9)
        new_rely = random.uniform(0.1, 0.9)
        button.place(relx=new_relx, rely=new_rely, anchor=CENTER)

# 创建按钮
button = Button(win, text="Click Me To Print SomeThing", command=btn1)
button.place(relx=0.5, rely=0.5, anchor=CENTER)

# 绑定窗口鼠标移动事件
win.bind("<Motion>", check_mouse_pos)

win.mainloop()

你可以根据使用需求调整RESPONSE_RADIUS的数值,数值越大按钮的响应范围越大,越容易触发移动;修改random.uniform的参数可以调整按钮移动的边界范围。

内容的提问来源于stack exchange,提问作者Minecraft1234

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 04:45:00