You need to enable JavaScript to run this app. Python Tkinter报错Tk is not defined,Open按钮触发的新窗口无密码控件如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

Python Tkinter报错Tk is not defined,Open按钮触发的新窗口无密码控件如何解决?

问题排查与修复方案

核心问题原因

  • 导入Tkinter时使用了别名tk,代码中直接调用Tk()、Label()等组件没有加tk.前缀,导致命名空间找不到对应类,触发“Tk is not defined”报错。
  • Tkinter程序仅允许存在1个Tk()主窗口实例,你已经创建了全局主窗口MyProgram,且在Open函数中已经用Toplevel创建了子窗口newWindow,额外新建的top = Tk()属于冗余逻辑,控件全部绑定到了无效的top对象上,自然不会在弹出的子窗口中渲染。
  • 子窗口不需要单独调用mainloop(),全局的主窗口事件循环已经覆盖所有子窗口,重复调用会引发事件逻辑冲突。
  • 原代码使用了//作为注释符号,Python规范注释符为#。

修正后可运行代码

import tkinter as tk

def Open():
    newWindow = tk.Toplevel(MyProgram)
    # 设置子窗口尺寸
    newWindow.geometry("450x300")
    # 用户名标签
    user_name = tk.Label(newWindow, text = "Username").place(x = 40, y = 60)  
    # 密码标签
    user_password = tk.Label(newWindow, text = "Password").place(x = 40, y = 100)  
    # 提交按钮
    submit_button = tk.Button(newWindow, text = "Submit").place(x = 40, y = 130)
    # 用户名输入框
    user_name_input_area = tk.Entry(newWindow, width = 30).place(x = 110, y = 60)  
    # 密码输入框
    user_password_entry_area = tk.Entry(newWindow, width = 30).place(x = 110, y = 100)  

# 主窗口初始化
MyProgram = tk.Tk()
frame = tk.Frame(MyProgram)
frame.pack()
# 退出按钮
button = tk.Button(frame, 
                   text="QUIT", 
                   fg="red",
                   command=quit)
button.pack(side=tk.LEFT)
# 打开子窗口按钮
slogan = tk.Button(frame,
                   text="Open",
                   command=Open)
slogan.pack(side=tk.LEFT)

MyProgram.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 12:27:04