如何在新窗口中显示图形?Tkinter GUI



这是我的图函数和一个用于打开新窗口的示例函数的代码。我找不到如何在新窗口上打印图形。我尝试了其他方法,但只发现自己能够分别提交两个命令。知道如何在新窗口上打印图形吗?

def plot(): 
# the figure that will contain the plot 
fig = Figure(figsize = (5, 5), dpi = 100) 
df = pd.DataFrame(np.random.randint(0,1000,size=(20, 2)), columns= 
('Storage Units (kWh)', 'Power Plants (kW)'))
y = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
fig, axes = plt.subplots(ncols=2, sharey=True)
plt.suptitle('Optimal Actions')
plt.yticks(np.arange(min(y), max(y)+1, 1.0))
axes[0].invert_yaxis
axes[0].xaxis.set_label_position('top') 
axes[1].xaxis.set_label_position('top')
axes[0].yaxis.set_label_coords(1.15,1.02)
axes[0].barh(y, df['Storage Units (kWh)'], align='center', color='red')
axes[1].barh(y, df['Power Plants (kW)'], align='center', color='blue')
axes[0].invert_xaxis()
axes[0].yaxis.tick_right()
axes[0].set_xlabel('Storage Units (kWh)')
axes[1].set_xlabel('Power Plants (kW)')
axes[0].set_ylabel('Year')
# creating the Tkinter canvas 
# containing the Matplotlib figure 
canvas = FigureCanvasTkAgg(fig, master = window)   
canvas.draw() 
# placing the canvas on the Tkinter window 
canvas.get_tk_widget().pack() 
def create_window():
newwindow = tk.Toplevel(window)
pbutton = tk.Button(frame4,
text = "Plot",
command = lambda:[create_window(), plot()]).pack(side = 
"right")

您可以将newwindow传递给plot()函数:

def plot(parent):
...
canvas = FigureCanvasTkAgg(fig, master=parent)
...
def create_window():
newwindow = tk.Toplevel(window)
return newwindow
...
pbutton = tk.Button(frame4, text='Plot', lambda: plot(create_window()))
pbutton.pack(side='right')

最新更新