【问题标题】:Replace FigureCanvasTkAgg content on repaeted button press in Tkinter在 Tkinter 中重复按下按钮时替换 FigureCanvasTkAgg 内容
【发布时间】:2020-04-01 18:21:20
【问题描述】:

我一直在解决这个问题。我有一个分析按钮,它调用一个函数,该函数使用 matplotlib 创建一个复杂的图形,并将其作为 FigureCanvasTkAgg 放入我的 tkinter GUI 上的 Frame 中。 在 GUI 中,用户应该能够再次按下分析并再次运行分析,并且现有的图形和工具栏应该被新的替换。使用我的代码,每次按下新按钮时工具栏都会堆积起来,并且数字也会开始堆叠。

root = tk.ThemedTk()
analyse_button.place(x=70, y=350, anchor='w', height=30, width=210)

def analysis()
    ...
    f = Figure(figsize=(8, 5), dpi=125)
    a = f.add_subplot(111)
    graph = nx.Graph()
    ...

    frm = Frame(root, width=700, height=500)
    frm.place(x=240, y=420, anchor='w')

    canvas = FigureCanvasTkAgg(f, master=frm)
    canvas.draw()
    canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)

    toolbar = NavigationToolbar2Tk(canvas, root)
    toolbar.configure(bg="white")
    toolbar.update()
    canvas._tkcanvas.pack()

...
root.mainloop()

我尝试检查frmtoolbar 是否已经存在,以便在创建新的之前销毁它们。

if frm.winfo_exists():
    if toolbar.winfo_exists():
        frm.destroy()
        toolbar.destroy()

这当然给了我frmtoolbar 没有定义的错误。

关于如何解决这个问题的任何建议?

【问题讨论】:

    标签: python-3.x button canvas tkinter configuration


    【解决方案1】:

    您似乎不知道局部变量是什么。此外,您的变量一开始并未声明。最简单的解决方案(虽然通常很愚蠢)是使用 sth.像这样:

    root = tk.ThemedTk()
    analyse_button.place(x=70, y=350, anchor='w', height=30, width=210)
    
    frm = None
    toolbar = None
    
    def analysis():
        global frm, toolbar
        if rfm is not None and frm.winfo_exists():
            if toolbar is not None and toolbar.winfo_exists():
                frm.destroy()
                toolbar.destroy()
        ...
        f = Figure(figsize=(8, 5), dpi=125)
        a = f.add_subplot(111)
        graph = nx.Graph()
        ...
    
        frm = Frame(root, width=700, height=500)
        frm.place(x=240, y=420, anchor='w')
    
        canvas = FigureCanvasTkAgg(f, master=frm)
        canvas.draw()
        canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
    
        toolbar = NavigationToolbar2Tk(canvas, root)
        toolbar.configure(bg="white")
        toolbar.update()
        canvas._tkcanvas.pack()
    
    ...
    root.mainloop()
    

    使用globalnonlocal 关键字通常是一种不好的做法,学习简单的OOP 原则来避免它。希望对您有所帮助!

    【讨论】:

    • 谢谢,它有帮助。我将研究如何使这项工作更干净。我对函数的使用确实需要改进。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多