Reputation: 53
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()
Upvotes: 0
Views: 1344
Reputation: 1207
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: Universal widget methods
Although this is considered impolite, it does what you were trying to achieve here. Make sure to also set focus on the toplevel window:
import tkinter as tk
root = tk.Tk()
root.geometry("300x300")
def show_message():
dialog = tk.Toplevel(root)
close = tk.Button(dialog,text="close",command=dialog.destroy)
close.pack()
dialog.focus_set()
dialog.grab_set_global()
button = tk.Button(root,text="Click here", command=show_message)
button.pack()
root.mainloop()
Tkinter's messagebox
widget can do what you are trying to achieve here. While the messagebox is visible, you won't be able to focus on the root window.
import tkinter as tk
from tkinter import messagebox as mb
root = tk.Tk()
def dialog(*args):
mb.showinfo("Dialog", "Hello World!")
btn = tk.Button(root, text="Click me", command=dialog)
btn.pack()
root.mainloop()
Upvotes: 1
Reputation: 7006
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.
Upvotes: 1