错误的窗口路径名“。!toplevel

时间:2019-10-06 09:33:48

标签: python tkinter import

我正在尝试制作一个用于登录的程序,它将带您进入主菜单,但是主菜单出现问题。我认为这可能与删除根窗口有关,但我没有尝试过。当所有代码都在一个文件中时,此代码有效,但我希望它们在单独的文件中。

from tkinter import *

import sys

import sqlite3


def main_menu(root):

    global Main

    if 'normal' == root.state():

        Main = Toplevel()

        Main.title("Main Menu")

        lbl_main = Label(Main, text = "Welcome to the main menu").pack()

        btn_back = Button(Main, text = "Back", command = Back(root)).pack(pady=20, fill = X)

        root.withdraw()


def Back(root):

    Main.destroy()

    if 'normal' != Main.state():

        root.deiconify()

这些功能都在导入到主文件的单独文件中。每次我尝试运行主文件时,登录部分都工作正常,但是在加载主菜单时,会出现此错误代码。

Exception in Tkinter callback

Traceback (most recent call last):

  File "C:\Users\*\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__

    return self.func(*args)

  File "C:\Users\*\LOG IN 3.py", line 51, in login

    mainmenu.main_menu(root)

  File "C:\Users\*\mainmenu.py", line 13, in main_menu

    btn_back = Button(Main, text = "Back", command = 
Back(root)).pack(pady=20, fill = X)

  File "C:\Users\*\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 2369, in __init__

    Widget.__init__(self, master, 'button', cnf, kw)

  File "C:\Users\*\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 2299, in __init__

    (widgetName, self._w) + extra + self._options(cnf))

_tkinter.TclError: bad window path name ".!toplevel"

这是使用从主菜单代码导入的功能的代码。

def login():

    database() 

    if u.get() == "" or p.get() == "": # getting the user input

        lbl_1 = Label(root, text = "Please enter your details.").pack()

    else:

        cursor.execute("SELECT * from STUDENT WHERE username = '%s' AND password = '%s'" %(u.get(), p.get()))

        lbl_1 = ""

        if cursor.fetchone() is not None:

            lbl_1 = Label(root, text = "Accepted").pack()

            mainmenu.main_menu(root)

        else:

            lbl_1 = Label(root, text = "Invalid").pack()

如果有人可以帮助我,那就太好了。 如果解释不清楚,我深表歉意。我将尝试与任何有疑问的人联系起来。

1 个答案:

答案 0 :(得分:0)

我认为您尝试在Back中做的是显示缩回的根(如果最小化的话)。 您应该在root而不是main上调用状态,因为main已被破坏。

def Back(root):
    Main.destroy()
    if 'normal' != root.state():
        root.deiconify()

ps:在main_menu中,应将命令设置为部分方法,而不是Back的结果。可以在单击按钮时而不是在绘制main_menu时调用Back。

from functools import partial
def main_menu(root):
    ...
    if 'normal' == root.state():
        ...
        btn_back = Button(Main, text = "Back", command = partial(Back, root)).pack(pady=20, fill = X)
        ...