ASM
ASM

Reputation: 79

Python3 tkinter - New window with class is blank + new window contents in original window

I am dabbling in tkinter's possibilities to make a simple application that shows a "Enter password" little window upon startup. But the weirdest behaviour started to happen...

mainWindow.py

import tkinter as tk
import password

class mainWindow(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)

        self.title("mainWindow")
        self.geometry("{0}x{1}+20+20".format(50,50))

if __name__ == "__main__":
    mainW = mainWindow()

    passW = password.passwordWindow()
    passW.resizable(False, False)
    passW.attributes("-topmost", True)
    passW.mainloop()

password.py

import tkinter as tk import mainWindow

class passwordWindow(tk.Tk):
    def __init__(self):

        tk.Tk.__init__(self)
        self.title("Password")

        self.frame = tk.Frame(height=2, bd=1, relief=tk.SUNKEN)
        self.frame.pack(fill=tk.X, padx=5, pady=5)

        self.label = tk.Label(self.frame, text="This Label is packed\nin the Password's Frame.")
        self.label.pack(fill=tk.BOTH, expand=1)

Result: uhhhh...

Needless to say, it's not the desired effect. The "Label" part should be on the password window! Any clue why am I getting this result? Thanks in advance!!

Upvotes: 0

Views: 99

Answers (1)

Mike - SMT
Mike - SMT

Reputation: 15226

The 1st porblem I can see is you are using Tk() twice here. Instead of using Tk() for a new window use Toplevel() instead. Toplevel is meant to be used to create new windows after the main window has been generated.

Next we need to pass the root window to the password class so we can use it as the top level of the main windows instance.

So in short your code should look like this:

mainWindow.py

import tkinter as tk
import password

class mainWindow(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)

        self.title("mainWindow")
        self.geometry("{0}x{1}+20+20".format(50,50))

if __name__ == "__main__":
    mainW = mainWindow()
    passW = password.passwordWindow(mainW)
    passW.resizable(False, False)
    passW.attributes("-topmost", True)
    mainW.mainloop()

password.py

import tkinter as tk
import mainWindow

class passwordWindow(tk.Toplevel):

    def __init__(self, controller):
        tk.Toplevel.__init__(self, controller)
        self.title("Password")

        self.frame = tk.Frame(self, height=2, bd=1, relief=tk.SUNKEN)
        self.frame.pack(fill=tk.X, padx=5, pady=5)

        self.label = tk.Label(self, text="This Label is packed\nin the Password's Frame.")
        self.label.pack(fill=tk.BOTH, expand=1)

Results:

enter image description here

Upvotes: 2

Related Questions