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

Tkinter中第二个窗口无法获取输入值的问题求助

问题修复方案

你的问题主要由两个核心问题导致,以下是具体修复步骤及优化后的代码:

关键问题分析

  1. 多Tk实例冲突:Tkinter应用仅允许一个主Tk()实例,创建第二个Tk()会生成独立的Tcl解释器,导致全局变量selection的绑定上下文混乱,无法正常传递输入值。
  2. 事件循环未启动:原代码中display.mainloop缺少括号,导致第二个窗口的事件循环未运行,用户输入和按钮点击无法触发对应逻辑。

修复后的完整代码

from tkinter import *

def Admin(selection_var):
    value = selection_var.get()
    print("hi", value)
    if value == '1':
        print("1")
    elif value == '2':
        print("2")
    elif value == '3':
        print("3")
    elif value == '4':
        print("4")
    elif value == '5':
        print("5")
    elif value == '6':
        print("6")
    elif value == '7':
        print("7")

incorrect = 0
def login():
    # 跳过用户名密码验证逻辑
    AdminF()

def Loginform():
    global login_screen
    login_screen = Tk()
    login_screen.title("Login Form")
    login_screen.geometry("300x250")

    global message, username, password
    username = StringVar()
    password = StringVar()
    message = StringVar()

    Label(login_screen, width="300", text="Please enter details below", bg="orange", fg="white").pack()
    Label(login_screen, text="Username * ").place(x=20,y=40)
    Entry(login_screen, textvariable=username).place(x=90,y=42)
    Label(login_screen, text="Password * ").place(x=20,y=80)
    Entry(login_screen, textvariable=password, show="*").place(x=90,y=82)
    Button(login_screen, text="Login", width=10, height=1, bg="orange", command=login).place(x=105,y=130)
    Label(login_screen, text="", textvariable=message).place(x=95,y=100)
    login_screen.mainloop()

class AdminF:
    def __init__(self):
        self.selection = StringVar()
        # 使用Toplevel创建子窗口,共享主窗口的上下文
        self.display = Toplevel()
        self.display.title("ADMIN")
        self.display.geometry("300x250")
        
        Label(self.display, width="300", text="Welcome Admin", bg="orange", fg="white").pack()
        Label(self.display, width="300", text="Please Select a Number", bg="white", fg="black").pack()
        Label(self.display, width="300", text="\n1.print 1\n2.print 2 \n3.print 3\n4.print 4 \n5.print 5\n6.print 6 \n7.print 7 ", bg="orange", fg="white").pack()
        
        Entry(self.display, textvariable=self.selection).place(x=20,y=180, width="260")
        # 通过lambda将实例属性传递给Admin函数,避免全局变量依赖
        Button(self.display, text="submit", width=10, height=1, bg="orange", command=lambda: Admin(self.selection)).place(x=105,y=210)
        self.display.mainloop()

Loginform()

修改说明

  • 用Toplevel()替代第二个窗口的Tk(),确保变量上下文与主窗口一致
  • 补全mainloop()的括号,启动子窗口的事件循环
  • 将selection改为AdminF类的实例属性,通过lambda表达式传递给Admin函数,消除全局变量依赖
  • 移除了未使用的import time语句

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 09:45:45