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

进程未启动任何内容即终止问题排查(附Python代码)

代码无法启动窗口的原因及修复方案

核心问题

代码仅定义了start_game()函数,但从未调用该函数,程序执行完函数定义后直接终止,自然不会弹出任何窗口。

函数内部的其他错误

  • 按钮添加错误:canvas.create_window(250, 330, window=start_game)将函数对象传给了window参数,正确做法是传入创建好的按钮组件select_btn。
  • 图片引用丢失:logo_img是局部变量,函数执行完毕后会被Python垃圾回收,导致图片无法显示,需将其绑定到窗口或画布的属性上避免被回收。
  • 冗余代码:title = screen.title('Math Duel')无意义,screen.title()是无返回值的方法,直接调用即可。

修复后的代码

from tkinter import *
from tkinter import filedialog

# Functions
def start_game():
    screen = Tk()
    screen.title('Math Duel')
    canvas = Canvas(screen, width=500, height=500)
    canvas.pack()

    # image logo
    logo_img = PhotoImage(file='methbettle.png')
    logo_img = logo_img.subsample(2, 2)
    canvas.create_image(250, 150, image=logo_img)
    canvas.logo_img = logo_img  # 绑定到canvas属性,防止垃圾回收

    # Select Path for saving the file
    path_label = Label(screen, text="Single/Multiplayer", font=('Arial', 15))
    select_btn = Button(screen, text="Launch", bg='red', padx=22, pady=5, font=('Arial', 15))
    # Add to window
    canvas.create_window(250, 280, window=path_label)
    canvas.create_window(250, 330, window=select_btn)  # 传入正确的按钮组件

    screen.mainloop()

# 调用启动函数,触发窗口创建
start_game()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 09:15:30