How to close current tkinter window and open a new tkinter window when the user inputs test into a tkinter Entry widget

Viewed 81

I would like to close the current tkinter window, and open a new tkinter window when the user inputs text into an entry widget. That might sound confusing so let me explain.

First tkinter window:

First window

When the user inputs text into the Entry widget, I would like this current window to close and the second window to open with the text the user entered displayed in a label widget.

Second window:

Window 2

Here is my current code:

from tkinter import *
user_input = ''

class Startup_window:
    def __init__(self, master):
        self.master = master

        master.title('Window 1')

        def get_input(event):
            global user_input
            # Gets the user input from the Entry widget
            user_input = self.input.get()
            # Clears Entry widget
            self.input.delete(0, END)
            master.destroy()

        self.label = Label(master, text='Input:')
        self.label.grid(row=0, column=0)

        self.input = Entry(master)
        self.input.grid(row=0, column=1)
        self.input.focus()

        self.input.bind("<Return>", get_input)


class Main_window:
    def __init__(self, master):
        self.master = master

        master.title('Window 2')

        self.label = Label(master, text="You've entered (user_input)" + user_input)
        self.label.pack()

root = Tk()

startup_window = Startup_window(root)
if user_input != '':
    main_window = Main_window(root)

mainloop()

I am new to tkinter and object oriented programming so any help would be greatly appreciated!

1 Answers

This would work for you. As @CoolCloud mentioned, the if condition will be checked only once. Because mainloop() actually waits for events to be triggered (maybe through some buttons or whatever), NOT that it executes the blocks of code over and over again

import tkinter as tk

class MainApp():
    def __init__(self, root):
        self.root = root
        self.inputBox = tk.Entry(self.root)
        self.inputBox.pack()
        self.inputBox.bind('<Return>', self.checkInput)

    def checkInput(self, args):
        if self.inputBox.get() != '':
            userVal = self.inputBox.get()
            self.root.destroy() # try root.quit if it doesn't work
            newWindow = tk.Tk()
            myLabel = tk.Label(newWindow, text='You entered: ' + userVal)
            myLabel.pack()

win = tk.Tk()
MainApp(win)
win.mainloop()
Related