【问题标题】:Avoid multiple windows of the same kind避免使用多个相同类型的窗口
【发布时间】:2018-10-24 20:52:21
【问题描述】:

我的目标是制作一个交互式条形图。我想打开一个包含文本的窗口。这将在用户单击其中一个条时发生。我开始玩了一下。在以下示例中,如果单击左侧栏,则会弹出一个包含文本的窗口。我遇到的问题,我只想让窗户打开一次。因此,如果您再次单击左侧栏,我不想打开第二个窗口。因此我的问题是,如何检查窗口是否已经存在并避免多个相同类型的窗口。我已经找到了关于这个主题的帖子,但我不明白解决方案,只是解释得很差。

非常感谢您的帮助。

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()

【问题讨论】:

  • 您可以在创建窗口和销毁设置变量时添加一个变量并将其设置为True。或者使用单例。
  • 你说得对,也许这是解决我的问题的最简单方法。谢谢!

标签: python windows tkinter


【解决方案1】:

与此同时,我找到了解决问题的方法。就像 MediaEU 说的,我使用了一个我设置为真或假的变量。然而,一个重要的“技巧”是使用方法 state()。 如果主窗口打开,state() 返回“正常”。如果主窗口关闭 state() 将引发异常。作为初学者,我花了相当长的时间来弄清楚。 这是我的建议:

class info_window:
    def __init__(self, rect): # has an argument rect, for a specific bar in your plot
        self.rect = rect
        self.win_open = False
        self.state = 'normal'
        self.temp = self.rect.figure.canvas.mpl_connect('button_press_event', self)

    def label(self):
        self.label1 = ttk.Label(self.win, text ="Test1").grid(column=0,row=0)
        self.label2 = ttk.Label(self.win, text ="Test2").grid(column=0,row=1)
        self.label3 = ttk.Label(self.win, text ="Test3").grid(column=0,row=2)

    def __call__(self, event):
        cont, att = self.rect.contains(event) 
        try:                    # here is the "trick", in case window was closed self.win.state() throws an exception
            self.win.state()
        except:                 # setting win_open to False ensures that a window can be opened again
            self.win_open = False
        if cont == True:    
            if self.win_open == False: # if window does not exist, create it
                self.win = tk.Tk()
                self.label()
                self.win_open = True # as long as window is open, you can't create it again

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多