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

Tkinter调用exit_confirmation函数时出现pyimageX not found错误求助

解决Tkinter中"pyimageX not found"错误的方案

错误原因

  • Tkinter要求整个应用只能有一个主Tk()实例,你创建了第二个Tk()窗口,导致主窗口加载的图片资源无法在新窗口中访问。
  • 使用exit作为变量名覆盖了Python内置的exit()函数,会引发后续逻辑错误。
  • quit_game函数中调用destroy时未加括号,实际并未执行窗口销毁操作。

修改后的代码

from tkinter import *
import random

root = Tk()

# 定义图片资源
background = PhotoImage(file='background.png')
win_screen_image = PhotoImage(file='win_screen.png')
lose_screen_image = PhotoImage(file='lose_screen.png')
exit_confirmation_image = PhotoImage(file='exit_confirmation.gif')

def quit_game():
    # 销毁退出确认窗口和主窗口
    exit_win.destroy()
    root.destroy()

# 退出确认窗口函数
def exit_confirmation():
    global exit_win
    # 使用Toplevel创建子窗口,而非新的Tk实例
    exit_win = Toplevel(root)
    # 禁止在确认窗口关闭前操作主窗口
    exit_win.grab_set()
    confirmtation_canvas = Canvas(exit_win, height=202, width=360)
    confirmtation_canvas.pack()
    confirmtation_canvas.create_image(0, 0, image=exit_confirmation_image, anchor='nw')
    
    # 添加确认/取消按钮示例
    confirm_btn = Button(exit_win, text="确认退出", command=quit_game, font='Calibri 14')
    confirm_btn.pack(side=LEFT, padx=20, pady=10)
    cancel_btn = Button(exit_win, text="取消", command=exit_win.destroy, font='Calibri 14')
    cancel_btn.pack(side=RIGHT, padx=20, pady=10)

# 初始界面画布
def introduction_canvas():
    c = Canvas(root, height=720, width=1280)
    c.pack()

    # 放置背景图
    c.create_image(0, 0, image=background, anchor='nw')
    
    # 介绍文本
    intro_text = c.create_text(240, 80, font='Calibri 18', fill='white', 
                              text='     Welcome, Witcher\nPlease Enter Your Name:')
    
    # 名字输入框
    name = StringVar()
    name_entry = Entry(root, textvariable=name, font='Calibri 16')
    create_name_entry = c.create_window(238, 136, window=name_entry)

    # 确认按钮
    confirm_button = Button(c, text='Confirm', command=rules_canvas, font='Calibri 18')
    create_confirm_button = c.create_window(0, 0, window=confirm_button)

    # 退出按钮
    quit_button = Button(c, text='Quit', command=exit_confirmation, font='Calibri 18')
    create_quit_button = c.create_window(100, 100, window=quit_button)

def rules_canvas():
    pass

def game_canvas():
    pass

introduction_canvas()
root.mainloop()

关键修改点

  • 用Toplevel(root)替代Tk()创建退出确认窗口,作为主窗口的子窗口,共享主窗口的资源上下文。
  • 把变量名exit改为exit_win,避免覆盖Python内置函数。
  • 在quit_game中给destroy添加括号,确保执行窗口销毁操作。
  • 给退出确认窗口添加grab_set(),强制用户先处理该窗口,无法操作主窗口,提升交互逻辑合理性。
  • 补充了确认和取消按钮的实现,完善退出流程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 14:21:31