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

Python Tkinter按钮未被访问报错:骰子游戏按钮点击失效求助

问题修复方案

你的代码存在几个关键错误,直接导致按钮点击无响应,以下是逐一修正点:

  • 函数调用缺失括号:conti函数里仅写了GameWind和Intro.quit,这只是引用函数对象,并未执行函数。必须添加括号才能触发调用:

    • 将GameWind改为GameWind()
    • 将Intro.quit改为Intro.destroy()(quit()会退出整个Tkinter主循环,destroy()仅关闭当前窗口,更符合子窗口关闭的逻辑)
  • 按钮创建的参数与赋值问题:

    • tk.Button的第一个参数已经是父组件,无需额外写master=Intro
    • pack()方法返回None,若后续需要操作按钮,需将创建和布局分开:
      GameB = tk.Button(Intro, text="Continue", command=conti)
      GameB.pack()
      
  • 路径转义问题:Windows路径中的反斜杠\需要转义为\\,或使用原始字符串避免转义错误:

    photo = tk.PhotoImage(file=r"Sources Images\RULES.gif", master=Intro)
    
  • 多个Tk实例冲突:Tkinter不建议创建多个Tk()主窗口,会导致事件循环混乱。应使用Toplevel()创建子窗口,修改GameWind函数:

    def GameWind(parent):
        GW = tkinter.Toplevel(parent)
        GW.geometry("1000x1000")
        GW.resizable(0,0)
        GW.title("In Game")
    

    调用时传入当前窗口作为父组件:GameWind(Intro)

修正后的完整代码

import tkinter as tk
from tkinter import ttk

def GameWind(parent):
    GW = tk.Toplevel(parent)
    GW.geometry("1000x1000")
    GW.resizable(0,0)
    GW.title("In Game")

# Introduce window
def Introduce():
    Intro = tk.Tk()
    Intro.geometry("700x300")
    Intro.resizable(0,0)
    Intro.title("Introduce")
    
    ttk.Label(Intro, text="...").pack()
    # 用原始字符串处理路径,避免转义错误
    photo = tk.PhotoImage(file=r"Sources Images\RULES.gif", master=Intro)
    img_label = ttk.Label(Intro, image=photo)
    img_label.pack()
    # 保留图片引用,防止被垃圾回收导致图片不显示
    img_label.image = photo
    
    def conti():
        GameWind(Intro)
        Intro.destroy()
    
    # 拆分按钮创建与布局步骤
    GameB = tk.Button(Intro, text="Continue", command=conti)
    GameB.pack()
    
    Intro.mainloop()

# 启动程序
Introduce()

额外补充:PhotoImage对象若没有被变量引用,会被Python垃圾回收机制清理,导致图片无法显示,因此需要给标签添加image属性保留引用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 12:17:23