Home > Software design >  Only opening a Window only when it already is not open in Tkinter
Only opening a Window only when it already is not open in Tkinter

Time:12-28

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

CodePudding user response:

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:

enter image description here

When you click Do Something will prevent open new window. Unless close the topelevel window and then open new window again

CodePudding user response:

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")
  • Related