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

开发鸡蛋接取游戏时,点击方向键create_image不水平移动求助

解决Tkinter中create_image元素无法通过方向键水平移动的问题

问题根源

  1. 对图像元素的坐标返回值理解错误
    create_image创建的图像元素,coords()仅返回中心点的(x, y)坐标,而非矩形元素的四个边界值。你的代码尝试解包四个变量,会直接触发ValueError,导致移动函数无法执行。
  2. 路径转义隐患
    图片路径中的\M可能引发转义异常,建议用原始字符串或双反斜杠处理路径。

修正后的完整代码

from tkinter import Tk, Canvas, PhotoImage

root = Tk()
root.geometry("800x500")
c = Canvas(root, width=800, height=500, bg="white")
c.pack()

catcher_width = 100
catcher_height = 100
catcher_startx = 800 / 2 - catcher_width / 2
catcher_starty = 500 - catcher_height - 20

# 用原始字符串避免路径转义问题
basket = PhotoImage(file=r'C:\Users\Mike\Downloads\basket.png') 
# 以中心点为锚点创建图像(默认行为)
catcher = c.create_image(catcher_startx + catcher_width/2, catcher_starty + catcher_height/2, image=basket)

def move_left(event):
    x, y = c.coords(catcher)
    # 计算左边界:中心点x减去半宽需大于0
    if x - catcher_width/2 > 0:
        c.move(catcher, -20, 0)

def move_right(event):
    x, y = c.coords(catcher)
    # 计算右边界:中心点x加上半宽需小于画布宽度
    if x + catcher_width/2 < 800:
        c.move(catcher, 20, 0)

c.bind("<Left>", move_left)
c.bind("<Right>", move_right)

c.focus_set()
root.mainloop()

可选优化:改用左上角锚点

如果觉得中心点计算边界麻烦,可以创建图像时指定anchor='nw'(左上角锚点),此时coords()返回左上角坐标,边界判断更直观:

# 以左上角为锚点创建图像
catcher = c.create_image(catcher_startx, catcher_starty, image=basket, anchor='nw')

def move_left(event):
    x, y = c.coords(catcher)
    if x > 0:
        c.move(catcher, -20, 0)

def move_right(event):
    x, y = c.coords(catcher)
    if x + catcher_width < 800:
        c.move(catcher, 20, 0)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 22:30:53