0

I'm currently creating a login system which connects to a main application. The user uses the log in system to log in through a series of window, and after this is done, the log in window should close and the main program should open.

I've created a small example of my project. The issue I'm getting is that StringVar() doesn't seem to work in the second window.

Code for the first window:

# Python program to create a window linking to the second window

from tkinter import *
import tkinter as tk
import test2


class Window(tk.Tk):

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

        frame = Frame(self)
        frame.grid()

        # creates a button which closes this window and opens the next
        button2 = Button(frame, text='next frame', command=lambda: self.open_window())
        button2.grid()

    def open_window(self):
        # runs the 'openWindow' function from the second file named 'test2'
        test2.openWindow(app, test2)


if __name__ == '__main__':
    app = Window()
    app.mainloop()

Code for the second window:

# Second window named 'test2' which is displayed after the button in the first window is pressed

from tkinter import *
import tkinter as tk

def openWindow(app, window):

    Application = window.Window2()
    app.withdraw()  # closes the first window
    Application.mainloop()  # opens the second window


class Window2(tk.Tk):

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

        frame = Frame(self)
        frame.grid()

        self.var = StringVar()  # creates the StringVar()
        self.var.set("default")
        # creates an entry which is linked to self.var
        entry = Entry(frame, textvar=self.var, width=50, bg='lightgrey', justify=LEFT)
        entry.grid(padx=16, ipady=20)

        # this button should print the contents of the entry widget
        button = Button(frame, text='print', command=lambda: self.print_var())
        button.grid()

    def print_var(self):
        # prints value of self.var
        print(self.var.get())

The problem I get is that when I press the button in the second window, it doesn't print the actual contents of the entry widget. I think this means that the StringVar() isn't working properly so doesn't link to the entry widget, but I'm not sure why this is happening.

amroman
  • 7
  • 2
  • 2
    It is because `self.var` and `entry` are in different `Tk()` instances. Avoid creating multiple instances of `Tk()` – acw1668 Dec 17 '20 at 10:32
  • @acw1668 How could you have two separate programs linked without having to use `TopLevel()` and also avoiding this problem? – amroman Dec 17 '20 at 10:39
  • Normally, the main window is the instance of `Tk()`, other windows are instances of `Toplevel()`. So for your case, `Window2` should inherit from `tk.Toplevel`. But if you insist to the original design, you can use `master` option of `StringVar()`: `self.var = tk.StringVar(master=self)`. – acw1668 Dec 17 '20 at 15:56

0 Answers0