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

Python Ursina模块If语句内修改变量后出现未定义问题

问题原因

这是Python全局变量作用域的标准规则导致的问题,和Ursina模块本身无关:

  • 如果在函数/方法内部对某个变量执行赋值操作,Python会默认将该变量识别为当前作用域的局部变量,不会自动引用上层的全局变量
  • 你的代码在input方法里写了XO = "O"、XO = "X"的赋值语句,Python就把XO判定为input方法的局部变量
  • 执行到if XO == "X"判断逻辑时,局部变量XO还没有完成赋值,自然就会抛出未定义的报错
解决方法

在input方法的开头添加global XO声明,明确告诉Python这个XO变量使用全局作用域的定义即可。
另外不建议在Ursina的事件回调里用time.sleep(),会卡住整个渲染线程,要做延迟销毁可以用Ursina自带的invoke函数实现。

修改后的完整可运行代码如下:

from ursina import *
app = Ursina()
window.title = "Game"
window.borderless = False
window.exit_button_visible = False

XO = "X"

class Tile(Button):
    def __init__(self, position = (-5, -5, 0), texture = "assets/tile.png"):
        super().__init__(
            parent = scene,
            model = "quad",
            color = color.lime,
            position = position,
            texture = texture
        )
    def input(self, key):
        global XO  # 新增全局变量声明
        if self.hovered:
            if key == "left mouse down":
                if XO == "X":
                    Tile(position = self.position, texture = "assets/tile_x")
                    XO = "O"
                else:
                    Tile(position = self.position, texture = "assets/tile_0")
                    XO = "X"
                # 替换time.sleep为Ursina原生的延迟调用,避免卡窗口
                invoke(destroy, self, delay=0.005)
                
for x in range(3):
    for y in range(3):
        block = Tile((x-1, y-1))
app.run()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 02:42:01