如何用另一个matplotlib图更新tkinter窗口

szqfcxe2  于 2023-04-21  发布在  其他
关注(0)|答案(1)|浏览(138)

我想创建一个tkinter窗口,显示matplotlib图形,而不需要创建一个新窗口。我可以通过销毁窗口来翻阅图形,但我想避免这样做,因为它非常烦人。

import tkinter as tk
from tkinter import *
from matplotlib.pyplot import *
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.figure import Figure

#global variables
global stopper
data = (([1,2,3,4,5], [1,2,3,4,5]), ([1,2,3,4,5],[5,4,3,2,1]))
window = tk.Tk()
window.geometry("500x500")

def Descision(event):
    print("go to next dataset")
    stopper.set(1)

for i in data:
    print(i)

    frame = Frame(window, width = 750, height = 750)    #make a new frame
    frame.pack()
    frame.place(anchor='center', relx=0.5, rely=0.5)
    fig = Figure(figsize = (5, 5), dpi = 100)

    stopper = IntVar(window, 0)     

    plot1 = fig.add_subplot(111)

    plot1.plot(i[0], i[1])

    canvas = FigureCanvasTkAgg(fig, master = window)

    canvas.draw()

    canvas.get_tk_widget().pack()

    window.bind("<Key>", lambda event : Descision(event))

    window.wait_variable(stopper)   #wait until user presses a key
    frame.destroy()
    #canvas.clear()     #"AttributeError: 'FigureCanvasTkAgg' object has no attribute 'clear'"

我想从data[0]生成的图形切换到data[1],但是在破坏框架后生成的图像是空白的。有人能解释一下我在这里误解了什么吗?

7nbnzgx9

7nbnzgx91#

像其他许多人一样,我把头撞在墙上一会儿,让它按照我想要的方式工作。希望这对外面的人有帮助!

#global variables
global stopper
data = (([1,2,3,4,5], [1,2,3,4,5]), ([1,2,3,4,5],[5,4,3,2,1]), ([1,2,3,4,5],[3,3,3,3,3]))
window = tk.Tk()
window.geometry("500x500")

frame = Frame(window, width = 750, height = 750)    #make a new frame & populate with a canvas
frame.pack()
frame.place(anchor='center', relx=0.5, rely=0.5)    #I don't understand this tbh
fig = Figure(figsize = (5, 5), dpi = 100)
canvas = FigureCanvasTkAgg(fig, master = window)

def Descision(event):
    print("go to next dataset")
    stopper.set(1)

for i in data:
    print(i)

    stopper = IntVar(window, 0)   
    plot1 = fig.add_subplot(111)    #(re)insert a subplot

    l = plot1.plot(i[0], i[1])      #plot on said subplot

    canvas.draw()                   #draw plot on the canvas

    canvas.get_tk_widget().pack()   #put it all together

    window.bind("<Key>", lambda event : Descision(event))   #call another method

    window.wait_variable(stopper)   #wait until user presses a key
    fig.clear() #take out the last graphed canvas ... if you leave it then the axis overlap

相关问题