I would like to know if Toplevel
window is opened or closed by the user manualy, with only one open button for opening the window. I tried to do it with winfo
, but for some reason it doesn't work properly.
from tkinter import *
from tkinter import messagebox
global top
top= None
global counter
counter = 1
global root
root = None
def window1():
root = Tk()
root.geometry("300x200")
root.title('Window1')
my_button = Button(root, text="Open Window", command=openWindow2)
my_button.pack(pady=50, padx=50)
root.mainloop()
def openWindow2():
global counter
if (counter < 2):
top = Toplevel()
top.geometry("300x200")
top.title('Window 2')
my_label = Label(top, text="New Window!", font=("Helvetica, 24"))
my_label.pack(pady=50, padx=50)
counter =1
else:
checkwind2()
def checkwind2():
if (top is not None) and Toplevel.winfo_exists(top) == 1:
#this situation never happens
print("Window is opened")
else:
print("Window is closed")
window1()
CodePudding user response:
It appears you put global
s in the wrong place and so the top
variable always appears to be None
.
If you want to edit a variable outside a function, you need to add global
inside the function.
Try this:
from tkinter import *
from tkinter import messagebox
top= None
counter = 1
root = None
def window1():
root = Tk()
root.geometry("300x200")
root.title('Window1')
my_button = Button(root, text="Open Window", command=openWindow2)
my_button.pack(pady=50, padx=50)
root.mainloop()
def openWindow2():
global top
global counter
print(counter)
if (counter < 2):
top = Toplevel()
top.geometry("300x200")
top.title('Window 2')
my_label = Label(top, text="New Window!", font=("Helvetica, 24"))
my_label.pack(pady=50, padx=50)
counter =1
else:
checkwind2()
def checkwind2():
if (top is not None) and Toplevel.winfo_exists(top) == 1:
print("Window is opened")
else:
print("Window is closed")
window1()