Python Forum
Avoid multiple windows of the same kind
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Avoid multiple windows of the same kind
#1
My goal is to have an interactive bar chart. I want to open a window containing a text. This shall happen when the user clicks on one of the bars. I started playing around a bit. In the following example, if you click on the left bar a window containing a text pops up. The problem I have, I only want to have the window opening once. So if you click a second time on the left bar, I don't want to open a second window. Therefore my question, how can I check if the window already exists and avoid multiple windows of the same kind.

Thank you very much for your help.

def on_press(event):
    cont,att = rect[0].contains(event)
    if cont == True:
        win = tk.Tk()
        label1 = ttk.Label(win, text ="Test1").grid(column=0,row=0)
        label2 = ttk.Label(win, text ="Test2").grid(column=0,row=1)
        label3 = ttk.Label(win, text ="Test3").grid(column=0,row=2)


fig = plt.figure()
ax = fig.add_subplot(111)
x = [1,2,3]
y = [10,20,5]
rect = ax.bar(x,y)



test = rect[0].figure.canvas.mpl_connect('button_press_event', on_press)

plt.show()
Reply
#2
You can add a boolean to remember if the window was already created
def on_press(event):
    if on_press.window_created:
        return
    cont,att = rect[0].contains(event)
    if cont == True:
        win = tk.Tk()
        on_press.window_created = True
        label1 = ttk.Label(win, text ="Test1").grid(column=0,row=0)
        label2 = ttk.Label(win, text ="Test2").grid(column=0,row=1)
        label3 = ttk.Label(win, text ="Test3").grid(column=0,row=2)
on_press.window_created = False
...
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Tkinter multiple windows in the same window tomro91 1 790 Oct-30-2023, 02:59 PM
Last Post: Larz60+
  'Your first program' type question, be kind davediamond 0 1,047 Apr-11-2022, 08:12 PM
Last Post: davediamond
  [Tkinter] Program with Multiple Windows - how to use Class: Riddle 1 2,937 Apr-09-2020, 08:30 PM
Last Post: Riddle
  What kind of widget is it? aquerci 1 1,783 Apr-05-2020, 05:37 PM
Last Post: DT2000
  [Tkinter] How to exit when multiple root windows. weatherman 4 5,461 May-10-2018, 11:52 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020