Tkinter gui 仅在调整 window 大小时绘制图形

Tkinter gui only plots figure when window is being resized

我有一个脚本可以将一个简单的情节嵌入到 Tkinter gui 中。有一个绘图按钮,当它按下时它似乎什么都不做,但如果 window 稍微调整大小,绘图就会弹出。 gui window 足够大以包含情节,我在这里做错了什么?

代码

print('\n'*3)
import tkinter as tk
import matplotlib.pyplot as plt  
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure

#MAKE ROOT WINDOW
root = tk.Tk()
root.title("Tab Widget")
#root.geometry("600x450")

#MAKE A FIGURE OBJECT
my_figure = Figure(figsize = (4, 4), dpi = 100) 

#MAKE A FRAME WIDGET
frame1 = tk.Frame(root, bd=2, relief=tk.GROOVE)
frame1.pack(side=tk.LEFT, anchor=tk.N, fill=tk.BOTH, expand=True)
frame2 = tk.Frame(root, bd=2, relief=tk.GROOVE)
frame2.pack(side=tk.RIGHT)

#MAKE A CANVAS OBJECT
my_canvas = FigureCanvasTkAgg(my_figure, master = frame1) # creating the Tkinter canvas containing the Matplotlib figure  

# TURN THE CANVAS OBJECT INTO A CANVAS WIDGET
my_canvas.get_tk_widget().pack() # placing the canvas on the Tkinter window
my_canvas.draw()

def plotData():
    plot1 = my_figure.add_subplot(111) # adding the subplot 
    x = [1,2,3,4,5]
    y = [11, 3, 6, 9,12]
    plot1.plot(x, y, marker='o', c='b')

# MAKE BUTTON TO PLOT GRAPH
button1 = tk.Button(frame2, text = "Plot", command = plotData, relief = tk.GROOVE, padx =20, pady =20 )
button1.pack(side="right")

root.mainloop()

期望的结果

一个 gui window 不需要调整大小就可以看到情节。

您需要在 plotData() 结束时调用 my_canvas.draw():

def plotData():
    plot1 = my_figure.add_subplot(111) # adding the subplot 
    x = [1,2,3,4,5]
    y = [11, 3, 6, 9,12]
    plot1.plot(x, y, marker='o', c='b')
    my_canvas.draw() # draw the graph