使用tkinter spinbox中的值单击按钮时,使用pyplot绘制线条

问题描述 投票:0回答:1

这是one asked before的后续问题。我有一个代码如下:

from tkinter import *

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure

class PlotClass():
    def __init__(self):
         fig = Figure(figsize=(5,5),dpi=70,facecolor='cyan')
         ax = fig.subplots()
         ax.set_title("Ttile")
         ax.set_ylabel("y")
         ax.set_xlabel("x")
         ax.set_xlim(100,9000)
         ax.set_ylim(130,-10)
         ax.set_facecolor("cyan")

         x = [125,250,500,1000,2000,4000,8000]
         ticks = [125,250,500,"1K","2K","4K","8K"]
         xm = [750,1500,3000,6000]

         ax.set_xscale('log', basex=2)
         ax.set_xticks(x)
         ax.set_xticks(xm, minor=True)
         ax.set_xticklabels(ticks)
         ax.set_xticklabels([""]*len(xm), minor=True)

         ax.yaxis.set_ticks([120,110,100,90,80,70,60,50,40,30,20,10,0,-10])

         self.line, = ax.plot([],[],'r+',markersize=15.0,mew=2)
         self.line2,= ax.plot([],[],'-o',markersize=15.0,mew=2)
         ax.grid(color="grey")
         ax.grid(axis="x", which='minor',color="grey", linestyle="--")
         self.canvas = canvas = FigureCanvasTkAgg(fig, master=master)
         canvas.show()
         canvas.get_tk_widget().grid(column=0,row=2,columnspan=3,rowspan=15)
         self.spin = Spinbox(master, from_=125,to=8000,command=self.action)
         self.spin.grid(column=5,row=2)

         self.spin2 = Spinbox(master, from_=-10,to=125,command=self.action)
         self.spin2.grid(column=5,row=3)

         self.button = Button(master, text="plot here",command=self.plot)
         self.button.grid(column=5,row=4)
    def ok(self, x=1000,y=20):
        self.line.set_data([x],[y])
        self.canvas.draw_idle()

    def action(self):
        self.ok(float(self.spin.get()),float(self.spin2.get()))

    def linecreate(self, x=1000,y=20):
        self.line2.set_data([x],[y])
        self.canvas.draw_idle()

    def plot(self):
        self.linecreate(float(self.spin.get()),float(self.spin2.get()))

master = Tk()
plotter = PlotClass()
plotter.ok(125,10)
master.mainloop()

它通过使用来自两个tkinter spinbox的值输入x和y轴来绘制图形,因为spinbox中的值会更改绘图重绘并根据旋转框提供的值更改标记位置。现在,我添加了一个tkinter按钮并将其链接到一个函数,该函数将使用来自旋转框的相同值绘制另一个绘图但现在我无法理解如何在按下按钮时不删除先前的绘图而绘制新绘图。我的意思是,在图形上绘制新位置(添加更多标记)而不删除按钮按下添加的先前绘图位置(先前标记)。就像按钮单击时一样,它会根据旋转框值继续添加新标记,而不会删除之前的标记。在上一个问题中,每次旋转箱值改变时都会移除现有的图并添加新的图,但现在我无法理解如何在不删除前一个图的情况下绘制新位置。

python matplotlib plot tkinter
1个回答
0
投票

您可以将新点添加到现有行的数据中。

def linecreate(self, x=1000,y=20):
    X,Y = self.line2.get_data()
    X = np.append(X,[x])
    Y = np.append(Y,[y])
    self.line2.set_data(X,Y)
    self.canvas.draw_idle()
© www.soinside.com 2019 - 2024. All rights reserved.