Python: How to disable main window while secondary window is open (Tkinter) - python

I would like to disable the main window of my text adventure program while the character creation window is up. I am relatively new to this. When I try my code below, the main window stays interactable even though the secondary window (creator) is open. There is no error that the console puts out, it just doesn't work is all.
def characterCreator():
global creator
creator = Tk()
creator.title('Character Creator')
creator.geometry('300x400')
while creator.state=='normal':
root.state='disabled'

You should create your creator window as an instance of tkinter.Toplevel() rather than declaring a new instance of Tk() altogether, then you can use grab_set to prevent the user from interacting with the root window while the creator window is open.
import tkinter as tk
root = tk.Tk()
# usual root configs like title and geometry go here
creator = tk.Toplevel(root) # the Toplevel window is a child of the root window
# creator geometry and title and so on go here
creator.grab_set() # keep window on top
if __name__ == '__main__':
root.mainloop()

Related

Only opening a Window only when it already is not open in Tkinter

I created a button in tkinter with its command being to create anew window. But I don't want it to create a new window every time I click the create a new window button. I want to tell the program to open the new window only if it is not already open. If somewhere in the background the window is already open and the user presses the create a new window button I want it to move that window on the first layer of the user's screen (bringing it upfront from all the other open windows).
Here is my code --
def main():
main_bg = "Gray"
main_fg = "White"
import tkinter as tk
employees = []
window = tk.Tk()
window.configure(bg=main_bg)
window.title("Business app")
window.geometry("1100x650")
def open_new_window():
random_window = tk.Toplevel(window)
random_window.configure(bg=main_bg)
random_window.geometry("600x600")
random_button = tk.Button(window, text="Do Something", font="Times 32", bg=main_bg, fg=main_fg, command=open_new_window)
random_button.pack()
window.mainloop()
if __name__ == "__main__":
main()
I have searched websites like Geeksforgeeks and this website but I could not find the solution I was looking for. Please help.
NOTE -- PLEASE DO NOT CLOSE THIS QUESTION AND POINT ME TOWARDS ANOTHER FORUM BECAUSE I HAVE CHECKED OTHERS IN THIS WEBSITE AS I MENTIONED ABOVE
Added grab_set() will prevent open new window again.
def open_new_window():
random_window = tk.Toplevel(window)
#random_window.configure(bg=main_bg)
random_window.geometry("600x600")
random_window.grab_set()
Result:
When you click Do Something will prevent open new window. Unless close the topelevel window and then open new window again
You can save a reference to the widget, and then check the reference to see if it's set. If it is set, you can then call winfo_exists to check whether the reference points to an existing window.
random_window = None
...
def open_new_window():
global random_window
if random_window and random_window.winfo_exists():
# the window exists, so do nothing
return
random_window = tk.Toplevel(window)
random_window.configure(bg=main_bg)
random_window.geometry("600x600")

How to pause window to turn on another window?

I use tkinter and CTK:
I have created a page for login and I want to stop or use this page when the user is logged in, I want to show a new window and I want to resume the window when I want? How can I do that, I didn't know how to make it
I'll bite. Here's an example application that opens a second window when the user clicks a button on the main window, and disables interaction with the main window until the second window is closed.
Some configuration has been omitted for brevity, and I'm not using CTk here because I don't know how you've implemented it in your specific application - however, it should be easy enough to modify this example to work with CTk.
import tkinter as tk
from tkinter import ttk
class App(tk.Tk):
def __init__(self):
super().__init__()
self.open_button = ttk.Button(
self,
text='Open 2nd Window',
command=self.modal
)
self.open_button.pack()
def modal(self):
self.window = tk.Toplevel(self) # create new window
# bind a handler for when the user closes this window
self.window.protocol('WM_DELETE_WINDOW', self.on_close)
# disable interaction with the main (root) window
self.attributes('-disabled', True)
self.close_button = ttk.Button(
self.window,
text='Close Modal',
command=self.on_close
)
self.close_button.pack()
def on_close(self):
# re-enable interaction the root window
self.attributes('-disabled', False)
# close the modal window
self.window.destroy()
if __name__ == '__main__':
app = App()
app.mailoop() # run the app
In the future:
Provide code that shows you made a good-faith effort to solve the problem on your own
Don't post the same question multiple times within hours - if you need to make changes, edit the original question
If you mean you want to open up another window to do something before going back to the original window, you should consider using message box. Here is a link that goes over the types of messageboxes: https://docs.python.org/3/library/tkinter.messagebox.html.

Create multiple windows using one tkinter button in python

I am opening other windows from a single tkinter button as shown here:
https://www.pythontutorial.net/tkinter/tkinter-toplevel/
The code shown there is
import tkinter as tk
from tkinter import ttk
class Window(tk.Toplevel):
def __init__(self, parent):
super().__init__(parent)
self.geometry('300x100')
self.title('Toplevel Window')
ttk.Button(self,
text='Close',
command=self.destroy).pack(expand=True)
class App(tk.Tk):
def __init__(self):
super().__init__()
self.geometry('300x200')
self.title('Main Window')
# place a button on the root window
ttk.Button(self,
text='Open a window',
command=self.open_window).pack(expand=True)
def open_window(self):
window = Window(self)
window.grab_set()
if __name__ == "__main__":
app = App()
app.mainloop()
If I run this program, it is not possible to hit the "Open a window" button twice to get two Toplevel instances. I would like to get as many instances as I like to with only one button. Is this possible somehow?
Consider this line of code:
window.grab_set()
This is setting a grab on the first window that is created. That means that all events from both the keyboard and the mouse are funneled to the first window that is created. That means you can no longer click on the button in the root window until the grab has been removed. Note that if the window is destroyed, the grab is automatically removed.
Grabs are typically used when creating a modal dialog -- a dialog which requires user input before the program can continue. By doing a grab, you insure that the user can't interact with the main program until they've interacted with the dialog.
The solution is simple: remove the call to window.grab_set() if your goal is to be able to open multiple windows which can all be used at the same time.
Simply remove window.grab_set(). The grab_set() method routes all events for this application to this widget. Whatever events generated like button-click or keypress is directed to another window.
def open_window(self):
window = Window(self)

button open a duplicate window of the main page in a new window using python and tkinter in pycharm

How do you make a button open a duplicate window of the main page in a new window?
What would the python code be to do this with Tkinter?
For clarification, in notepad++ when you right click on the tab that you are in, it shows you a whole menu.
Then, there is a dropdown menu with an option that says, open in a new instance or move to a new instance.
This would then open the tab you selected into a new tab/window.
I haven't tried anything yet but I did look up about how to do this type of thing and there were no results on what exactly I wanted to do.
Can you try to show me an example of how what I need to do can be done?
Code:
Found Here
The simplest solution is to make your window be a subclass of Toplevel. Then, each time you need a new window, create a new instance of the class.
You can then leave the root window blank and hide it so that you only see your custom windows. It's important to make sure that you destroy the root window after the user has deleted the last application window, or else you'll end up with an invisible window that will be hard to kill.
Here is a bit of a contrived example:
import tkinter as tk
class AppWindow(tk.Toplevel):
def __init__(self, root):
tk.Toplevel.__init__(self, root)
self.root = root
menubar = tk.Menu(self)
windowMenu = tk.Menu(menubar)
windowMenu.add_command(label="New Window", command=self.new_window)
windowMenu.add_command(label="Quit", command=root.destroy)
menubar.add_cascade(label="Window", menu=windowMenu)
self.configure(menu=menubar)
self.text = tk.Text(self)
self.vsb = tk.Scrollbar(self, orient="vertical", command=self.text.yview)
self.text.configure(yscrollcommand=self.vsb.set)
self.vsb.pack(side="right", fill="y")
self.text.pack(side="left", fill="both", expand=True)
# call a function to destroy the root window when the last
# instance of AppWindow is destroyed
self.wm_protocol("WM_DELETE_WINDOW", self.exit_on_last_window)
def new_window(self):
AppWindow(self.root)
def exit_on_last_window(self):
"""Destroy the root window when no other windows exist"""
self.destroy()
if not any([window.winfo_exists() for window in self.root.winfo_children()]):
self.root.destroy()
def quit(self):
self.root.destroy()
# create the root, then hide it. The app will create its
# own windows as Toplevels
root = tk.Tk()
root.withdraw()
# create the first window, then start the event loop
AppWindow(root)
tk.mainloop()

How to prevent Tkinter window opening before being called?

When I run this script, two windows appear, one for the file selection and the Tkinter window. How can I change this so that the Tkinter window only opens after a file has been selected? Thanks
def main():
my_file = askopenfilename()
stage1()
def stage1():
master = Tk()
master.mainloop()
The window master does open only after the file dialog closure (try to change its title to check), the first window you see is the parent window of the file dialog. Indeed, the tkinter file dialogs are toplevel windows, so they cannot exist without a parent window. So the first window you see is the parent window of the file dialog.
The parent window can however be hidden using the withdraw method and then restored with deiconify:
from tkinter import Tk
from tkinter.filedialog import askopenfilename
def main():
master = Tk()
master.withdraw() # hide window
my_file = askopenfilename(parent=master)
master.deiconify() # show window
master.mainloop()
if __name__ == '__main__':
main()

Categories

Resources