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

Tkinter Canvas create_text文本移动时消失问题求解决方案

Tkinter GUI 文本移动消失问题修复

问题根因

文本消失是两处代码问题共同导致的:

  1. 左右移动的处理函数中,创建新文本的代码被放在了内层条件判断分支里,当位置不满足分支条件时,删除旧文本后不会生成新文本
  2. 即使满足分支条件执行了创建文本的代码,也遗漏了text="Welcome"参数,生成的是空文本,无法被看到

修复方案

直接修改process_left和process_right两个函数即可,修复后代码如下:

def process_left(self):
    self.canvas.delete("text")
    if self.x1 > 10:
        self.x1 -= 10
    if self.x1 > 60:
        self.x1 -= 10
    # 把创建文本的逻辑放到外层,补充text参数
    self.canvas.create_text(self.x1, self.y1, fill="black", text="Welcome", font=("Arial"), tags="text")


def process_right(self):
    self.canvas.delete("text")
    if self.x1 < 350:
        self.x1 += 10
    if self.x1 < 400:
        self.x1 += 10
    # 把创建文本的逻辑放到外层,补充text参数
    self.canvas.create_text(self.x1, self.y1, fill="black", text="Welcome", font=("Arial"), tags="text")

可选优化(非必须)

你当前切换背景的逻辑是每次都画新矩形覆盖、再重新生成文本,其实可以直接修改canvas的背景属性,代码更简洁也不会覆盖原有文本:

def process_radio_button(self):
    color_map = {1:"red", 2:"yellow", 3:"white", 4:"gray", 5:"green"}
    self.canvas.config(bg=color_map.get(self.v1.get(), "white"))

用这个替换原来的process_radio_button函数即可,不需要重复绘制矩形和文本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 02:54:03