Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Tkinter. Show only one copy of window

Tags:

python

tkinter

I have one problem. I have program which has been wrote on Tkinter.

import Tkinter as tk
import ttk


def about_window():
    print(root.child_window)

    if not root.child_window:
        top2 = tk.Toplevel(root)
        top2.title("About")
        top2.resizable(0,0)

        explanation = "This program is my test program"

        ttk.Label(top2,justify=tk.LEFT,text=explanation).pack(padx=5,pady=2)
        ttk.Button(top2,text='OK',width=10,command=top2.destroy).pack(pady=8)


root = tk.Tk()
root.resizable(0,0)

root.child_window = None
#print(root.child_window)

root.style = ttk.Style()
# ('clam', 'alt', 'default', 'classic')
root.style.theme_use("clam")

menu = tk.Menu(root)
root.config(menu=menu)

fm = tk.Menu(menu, tearoff=0)
menu.add_cascade(label="Settings",menu=fm)
fm.add_command(label="Preferances")

hm = tk.Menu(menu, tearoff=0)
menu.add_cascade(label="Help",menu=hm)
hm.add_command(label="About", command=about_window)
hm.add_command(label="Exit",command=root.quit)
#

tk.mainloop()

So I can click on "About" label and will see window:

enter image description here

But is it possible in Tkinter to disable any next launch of the same window?

enter image description here

I`ve tried this https://stackoverflow.com/a/24886806/2971192 but w/o success.

like image 386
ipeacocks Avatar asked Dec 06 '22 22:12

ipeacocks


1 Answers

One way is to make the child window transient to the root, so that you cannot interact with root until the child has been closed ( you don't need root.child_window here):

import Tkinter as tk
import ttk

def about_window(): 
    top2 = tk.Toplevel(root)
    top2.title("About")
    top2.resizable(0,0)

    explanation = "This program is my test program"

    ttk.Label(top2,justify=tk.LEFT,text=explanation).pack(padx=5,pady=2)
    ttk.Button(top2,text='OK',width=10,command=top2.destroy).pack(pady=8)

    top2.transient(root)
    top2.grab_set()
    root.wait_window(top2)

root = tk.Tk()
root.resizable(0,0)

root.style = ttk.Style()
# ('clam', 'alt', 'default', 'classic')
root.style.theme_use("clam")

menu = tk.Menu(root)
root.config(menu=menu)

fm = tk.Menu(menu, tearoff=0)
menu.add_cascade(label="Settings",menu=fm)
fm.add_command(label="Preferances")

hm = tk.Menu(menu, tearoff=0)
menu.add_cascade(label="Help",menu=hm)
hm.add_command(label="About", command=about_window)
hm.add_command(label="Exit",command=root.quit)
#

tk.mainloop()
like image 146
MrAlexBailey Avatar answered Dec 25 '22 08:12

MrAlexBailey