Python Forum
[Tkinter] Is it the right way to create a second window?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] Is it the right way to create a second window?
#1
hi guys,

I'm writing a graphical interface with Tkinter for some of my scripts and I would very like to know what do you think about my code because unfortunately I'm not an expert. I started to study Tkinter just recently.

my software should have a main window with many buttons, each of them associated to a specific menu (a new window). if you click one of them, the main window will close itself and a new window will open. if you close the latter, the main window will appear again, and from there you can choose another button to go ahead with a new window and so on. of course, if you close the main window, the software will be close definitivally.

to accomplish this goal, I wrote this code, it works but I wanted to know your opionions. from your side is it a good code? is it the right way to implement the behaviour that I just explained before?

#!/usr/bin/python3

from tkinter import *
from tkinter import ttk


class MainWindow:
    
    def __init__(self, master):
        # definisco gli attributi della finestra principale:     
        self.master = master
        master.title("My Software")
        master.iconbitmap("icon.ico")
        master.geometry("500x400+250+250")
        master.resizable (width=False, height=False)
        master.configure(background="#f0f0f0")
        # definisco i diversi widget di quest afinestra:
        ttk.Button(master, text = "Menu 1", command = self.__Open).pack()
    
    def __Open(self):
        ntw = Tk()
        app = SecondWindow(self.master, ntw)
        ntw.mainloop()

class SecondWindow:
    
    def __init__(self, mw, master):
        # chiudo la finestra principale:
        mw.destroy()        
        # definisco gli attributi della finestra "ntw":     
        self.master = master
        master.title("My Software - Menu 1")
        master.iconbitmap("icon.ico")
        master.geometry("500x400+250+250")
        master.resizable (width=False, height=False)
        master.configure(background="#f0f0f0")        
        # se chiudo la finestra:
        master.protocol("WM_DELETE_WINDOW", self.__CloseEvent)
    
    def __CloseEvent(self):
            self.master.destroy()
            main()
        
def main():
    root = Tk()
    app = MainWindow(root)
    root.mainloop()

if __name__ == "__main__":
    main()
I'm not sure about my code because to go ahead with a new window I must to destroy the main window, and create it again when I destroy the second window. maybe is it better don't destroy the main window?
Reply
#2
you should use TopLevel: https://effbot.org/tkinterbook/toplevel.htm
Reply
#3
Example of using Toplevel

#! /usr/bin/env python3

import tkinter as tk
from tkinter import messagebox
from functools import partial
import sys

class MainWindow:
    def __init__(self, parent):
        self.parent = parent

        btn = tk.Button(self.parent, text='Open New Window', fg='blue', \
                        command=partial(self.open_window), anchor='w')
        btn.grid(column=0, row=0, padx=10, pady=10)
        btn2 = tk.Button(self.parent, text='Close', fg='red', command=partial(self.close), anchor='w')
        btn2.grid(column=1,row=0, padx=10, pady=10)

        self.parent.protocol('WM_DELETE_WINDOW', self.close)

    def open_window(self):
        TopWindow(self.parent)
        self.parent.withdraw()

    def close(self):
        msg = messagebox.askokcancel('Quit Program', 'Do you wish to quit?')
        print(msg)
        if msg == True:
            sys.exit()


class TopWindow:
    def __init__(self, parent):
        self.parent=parent
        self.window = tk.Toplevel(parent=None)
        self.window.title('Top Level Window')
        self.window.geometry('300x200+10+10')
        btn = tk.Button(self.window, text='Close Window', fg='red', \
                        command=partial(self.window_close))
        btn.pack(side='bottom', pady=20)
        self.window.protocol('WM_DELETE_WINDOW', self.callback)

    def window_close(self):
        self.parent.deiconify()
        self.window.destroy()

    def callback(self):
        self.parent.deiconify()
        self.window.destroy()


def main():
    root = tk.Tk()
    root.title('Main Window')
    root.geometry('400x300+10+10')
    MainWindow(root)
    root.mainloop()

main()
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#4
thanks menator01, you have been very simple and clear!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Interaction between Matplotlib window, Python prompt and TKinter window NorbertMoussy 3 341 Mar-17-2024, 09:37 AM
Last Post: deanhystad
  tkinter window and turtle window error 1885 3 6,621 Nov-02-2019, 12:18 PM
Last Post: 1885
  PyGtk3, How to Create “title-changed” signal for Gtk.Window Widget? harun2525 2 6,034 May-01-2017, 07:59 AM
Last Post: harun2525
  update a variable in parent window after closing its toplevel window gray 5 8,974 Mar-20-2017, 10:35 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020