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

如何为Tkinter开发的Minecraft箱子模拟程序添加坐标绑定功能

实现方案

完整可运行代码

import tkinter as tk
from PIL import ImageTk, Image

# 配置参数
SLOT_COLS = 9  # Minecraft箱子默认每行9个槽位
SLOT_ROWS = 3  # 普通箱子填3,大箱子改成6即可
# 可先运行程序点击采集基准值后再修改下列参数
first_slot_x = 0  # 左上角第一个槽位的左上角X坐标
first_slot_y = 0  # 左上角第一个槽位的左上角Y坐标
slot_width = 36  # 单个槽位宽度,按实际截图尺寸调整
slot_height = 36 # 单个槽位高度,按实际截图尺寸调整
slots = []

# 点击事件处理函数
def on_click(event):
    # 获取相对于图片组件的点击坐标
    click_x = event.x
    click_y = event.y
    print(f"点击坐标:x={click_x}, y={click_y}")
    
    # 计算点击命中的槽位
    col = (click_x - first_slot_x) // slot_width
    row = (click_y - first_slot_y) // slot_height
    if 0 <= col < SLOT_COLS and 0 <= row < SLOT_ROWS:
        slot_index = row * SLOT_COLS + col
        # 计算当前槽位的边界和中心坐标
        slot_x1 = first_slot_x + col * slot_width
        slot_y1 = first_slot_y + row * slot_height
        slot_x2 = slot_x1 + slot_width
        slot_y2 = slot_y1 + slot_height
        slot_center_x = (slot_x1 + slot_x2) // 2
        slot_center_y = (slot_y1 + slot_y2) // 2
        print(f"命中槽位:第{row+1}行第{col+1}列,编号{slot_index},中心坐标({slot_center_x}, {slot_center_y})")
        
        # 自动存储槽位坐标
        if slot_index not in [s['index'] for s in slots]:
            slots.append({
                "index": slot_index,
                "x1": slot_x1,
                "y1": slot_y1,
                "x2": slot_x2,
                "y2": slot_y2,
                "center_x": slot_center_x,
                "center_y": slot_center_y
            })
            # 所有槽位采集完成后输出完整列表
            if len(slots) == SLOT_ROWS * SLOT_COLS:
                print("\n===== 所有槽位坐标采集完成 =====")
                for s in sorted(slots, key=lambda x:x['index']):
                    print(f"槽位{s['index']}: 中心坐标({s['center_x']}, {s['center_y']})")

window = tk.Tk()
window.title("Chest Simulator")
# 固定窗口尺寸避免坐标偏移,和截图尺寸保持一致最佳
window.geometry("1920x1080")
window.resizable(False, False)
window.configure(background='grey')

path = "chest.jpg"
img = Image.open(path)
# 如果截图尺寸和窗口不一致,放开下面注释做等比缩放保证坐标对应
# img = img.resize((1920, 1080), Image.Resampling.LANCZOS)
tk_img = ImageTk.PhotoImage(img)

panel = tk.Label(window, image = tk_img)
# 绑定鼠标左键点击事件
panel.bind("<Button-1>", on_click)
panel.pack(side = "bottom", fill = "both", expand = "yes")

window.mainloop()

使用步骤

  • 首次运行程序后,点击箱子界面左上角第一个槽位的左上角位置,记录打印的x、y值,填入first_slot_x、first_slot_y参数
  • 再点击第一行第二个槽位的左上角位置,计算两个x坐标的差值填入slot_width,两个y坐标的差值填入slot_height
  • 重新运行程序后,点击任意槽位都会自动识别槽位编号和坐标,所有槽位点击完成后会自动输出全量坐标列表

优化扩展

  • 如需自动点击功能,可将输出的槽位中心坐标传给pyautogui.click()方法直接调用
  • 可增加校准逻辑:程序启动后依次点击第一个槽位左上角、最后一个槽位右下角,自动计算槽位宽高和起始坐标,无需手动测量参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 02:15:03