Home > other >  How to create a new window like a message box?
How to create a new window like a message box?

Time:04-29

Hi guys hope you are doing well, i can't understand how to create in Tkinter a new window for example when i press a button that is like a message box, i mean creating a new window and i can't go back to the previous/main window until i close or press ok in the new window. How to simply create a new window and the user can't click the main window and can't go away until he close it just like happen in the message box ?? Thanks! Here is a basic starting code, how to bind this window that i'm talking about to the button?

from tkinter import *
window = Tk()
window.geometry("300x300")
button = Button(window,text="Click here")
button.pack()
window.mainloop()

CodePudding user response:

This type of dialog that takes control of the application is called "modal dialog". It can be implemented using the grab_set method.

from tkinter import *

def new_window():
    def close_window():
        dialog.grab_release()
        dialog.destroy()
    dialog = Toplevel(window)
    close = Button(dialog,text="close",command=close_window)
    close.pack()
    dialog.grab_set()
    

window = Tk()
window.geometry("300x300")
button = Button(window,text="Click here",command=new_window)
button.pack()
window.mainloop()

This code creates a new Toplevel window when you press "Click here". That dialog will grab all the events for the current application until you click the close button which will release the grab.

CodePudding user response:

Edit

As @scotty3785 have mentioned above, you can use the grab_set() method to keep the focus on your toplevel window. But still the root window will be draggable. But reading the documentation, I came across grab_set_global() method.

w.grab_set_global() Widget w grabs all events for the entire screen. This is considered impolite and should be used only in great need. Any other grab in force goes away.

Reference: test

  • Related