【发布时间】:2021-04-09 04:41:41
【问题描述】:
我需要一些关于我当前代码的帮助。我想通过 tkinter 创建一个窗口,并在我之前由 matplotlib 创建的画布中显示一个绘图。这一点我还没有达到。我的问题是我想通过点击一个按钮来清除这个画布。为了清除画布,我想在用绘图填充它之前对其进行初始化。
所以我的问题是:如何在创建的画布中填充绘图?
您可以在下面找到一个显示我的艺术状态的小代码。
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg,
NavigationToolbar2Tk)
def plot():
fig = Figure(figsize = (5, 5), dpi = 100)
y = [i**2 for i in range(101)]
# adding the subplot
plot1 = fig.add_subplot(111)
# plotting the graph
plot1.plot(y)
# creating the Tkinter canvas
# containing the Matplotlib figure
output = FigureCanvasTkAgg(fig, master = window)
output.draw()
# placing the canvas on the Tkinter window
output.get_tk_widget().pack()
def clear_plot():
canvas.delete('all')
# the main Tkinter window
window = Tk()
# setting the title
window.title('Plotting in Tkinter')
# dimensions of the main window
window.geometry("700x700")
canvas = Canvas(window, width=500, height=500)
canvas.pack()
# button that displays the plot
plot_button = Button(master = window, command = plot, height = 2, width = 10, text = "Plot")
clear_button = Button(master = window, command = clear_plot, height = 2, width = 10, text = "clear", background = "yellow")
# place the button
plot_button.pack()
clear_button.pack()
# run the gui
window.mainloop() ```
【问题讨论】:
-
你只是想一键清除剧情吗?
-
是的,在我点击“绘图”后,该图形应该出现在我创建的画布中的按钮上方(而不是在新画布窗口中的按钮下方)并且点击“清除”我希望拥有启动程序后再次清晰的画布
标签: python matplotlib tkinter tkinter-canvas