Skip to main content
 首页 » 编程设计

python之无法使用按钮和自定义数据更新 Tkinter matplotlib 图形

2025年05月04日16虾米姐

我正在创建一个利用 Tkinter 和 matplotlib 的程序。我有 2 个列表列表(一个用于 x 轴,一个用于 y 轴),我希望有一个按钮可以在列表中的列表之间切换。我从问题 Interactive plot based on Tkinter and matplotlib 中提取了大部分代码,但我无法在按下按钮时更新图表。我对使用类很陌生,理解它们有点困难。

tft 是我代码中的 x 数据 tf1 是 y 数据。

数据示例:

x-data = [[1,2,3,4,5],[10,11,13,15,12,19],[20,25,27]]

y-data = [[5.4,6,10,11,6],[4,6,8,34,20,12],[45,25,50]]

我下面的代码将绘制列表中的一个列表,但不会在按下按钮时在该列表中的列表之间切换。 event_num 的正确值也打印在命令窗口中(event_num 的问题已在之前的问题 here 中解决)。

没有出现错误,程序仅打印数字(按下按钮时),但不会使用列表中的新数据更新图表。

初步代码(没有问题——或者不应该有任何问题)

#Importing Modules 
import glob 
from Tkinter import * 
from PIL import Image 
from Text_File_breakdown import Text_File_breakdown 
import re 
import matplotlib.pyplot as plt 
from datetime import datetime 
 
#Initializing variables 
important_imgs=[] 
Image_dt=[] 
building=[] 
quick=[] 
num=0 
l=0 
match=[] 
 
#Getting the names of the image files 
image_names=glob.glob("C:\Carbonite\EL_36604.02_231694\*.jpeg") 
 
 
#image= Image.open(images_names[1]) 
#image.show() 
 
#Text_File_breakdown(file,voltage limit,pts after lim, pts before lim) 
tft,tf1,tf2=Text_File_breakdown('C:\Carbonite\EL_36604.02_231694.txt',3.0,5,5) 
#tft= time of voltages      tf1=Voltage signal 1             tf2=Voltage signal 2 
#Test Settings: 'C:\Carbonite\EL_36604.02_231694.txt',3.0,5,5 
 
 
#Getting the Dates from the image names 
for m in image_names: 
    Idt=re.search("([0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}.[0-9]{2}.[0-9]{2})", m) 
    Im_dat_tim=Idt.group(1) 
    Im_dat_tim=datetime.strptime(Im_dat_tim, '%Y-%m-%d %H.%M.%S') 
    Image_dt.append(Im_dat_tim) 
    Im_dat_tim=None 
 
#Looking for the smallest difference between the voltage and image dates and associating an index number (index of the image_names variable) with each voltage time 
for event in range(len(tft)): 
    for i in range(len(tft[event])): 
        diff=[tft[event][i]-Image_dt[0]] 
        diff.append(tft[event][i]-Image_dt[0]) 
        while abs(diff[l])>=abs(diff[l+1]): 
            l=l+1 
            diff.append(tft[event][i]-Image_dt[l]) 
        match.append(l) 
        l=0 
 
#Arranging the index numbers (for the image_names variable) in a list of lists like tft variable 
for count in range(len(tft)): 
    for new in range(len(tft[count])): 
        quick.append(match[num]) 
        num=num+1 
    building.append(quick) 
    quick=[] 
 
 
 
 
plt.close('all') 
fig, ax = plt.subplots(1) 
ax.plot(tft[1],tf1[1],'.') 
 
# rotate and align the tick labels so they look better 
fig.autofmt_xdate() 
 
# use a more precise date string for the x axis locations in the 
# toolbar 
import matplotlib.dates as mdates 
ax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d') 
plt.title('Single Event') 

问题所在的代码/部分代码的延续:

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg 
from matplotlib.figure import Figure 
import numpy as np 
 
class App: 
 
    def __init__(self, master): 
 
        self.event_num = 1 
 
        # Create a container 
        frame = Frame(master) 
 
        # Create 2 buttons 
        self.button_left = Button(frame,text="< Previous Event", 
                                    command=self.decrease) 
        self.button_left.grid(row=0,column=0) 
        self.button_right = Button(frame,text="Next Event >", 
                                    command=self.increase) 
        self.button_right.grid(row=0,column=1) 
 
 
        fig = Figure() 
        ax = fig.add_subplot(111) 
        fig.autofmt_xdate() 
        import matplotlib.dates as mdates 
        ax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d') 
        self.line, = ax.plot(tft[self.event_num],tf1[self.event_num],'.') 
 
 
        self.canvas = FigureCanvasTkAgg(fig,master=master) 
        self.canvas.show() 
        self.canvas.get_tk_widget().grid(row=1,column=0) 
        frame.grid(row=0,column=0) 
 
    def decrease(self): 
        self.event_num -= 1 
        print self.event_num 
        self.line, = ax.plot(tft[self.event_num],tf1[self.event_num],'.') 
        self.canvas.draw() 
        #self.canvas.draw(tft[self.event_num],tf1[self.event_num],'.') 
        #self.line.set_xdata(tft[event_num]) 
        #self.line.set_ydata(tf1[event_num]) 
 
 
 
    def increase(self): 
        self.event_num += 1         
        print self.event_num 
        self.line, = ax.plot(tft[self.event_num],tf1[self.event_num],'.') 
        self.canvas.draw() 
        #self.canvas.draw(tft[self.event_num],tf1[self.event_num],'.') 
        #self.set_xdata(tft[event_num]) 
        #self.set_ydata(tf1[event_num]) 
 
 
 
root = Tk() 
app = App(root) 
root.mainloop() 

请您参考如下方法:

问题是您不断地在与您想象的不同的一组轴上绘图。 self.line, = ax.plot(tft[self.event_num],tf1[self.event_num],'.') 指的是您在类外创建的轴,而不是类中的轴您在 App 类中创建的图形。这个问题可以通过创建 self.fig 和 self.ax 属性来解决:

class App: 
 
    def __init__(self, master): 
 
        self.event_num = 1 
 
        # Create a container 
        frame = Frame(master) 
 
        # Create 2 buttons 
        self.button_left = Button(frame,text="< Previous Event", 
                                    command=self.decrease) 
        self.button_left.grid(row=0,column=0) 
        self.button_right = Button(frame,text="Next Event >", 
                                    command=self.increase) 
        self.button_right.grid(row=0,column=1) 
 
 
        self.fig = Figure() 
        self.ax = self.fig.add_subplot(111) 
        self.fig.autofmt_xdate() 
        import matplotlib.dates as mdates 
        self.ax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d') 
        self.line, = self.ax.plot(tft[self.event_num],tf1[self.event_num],'.') 
 
 
        self.canvas = FigureCanvasTkAgg(self.fig,master=master) 
        self.canvas.show() 
        self.canvas.get_tk_widget().grid(row=1,column=0) 
        frame.grid(row=0,column=0) 
 
    def decrease(self): 
        self.event_num -= 1 
        print self.event_num 
        self.line, = self.ax.plot(tft[self.event_num],tf1[self.event_num],'.') 
        self.canvas.draw() 
 
    def increase(self): 
        self.event_num += 1         
        print self.event_num 
        self.line, = self.ax.plot(tft[self.event_num],tf1[self.event_num],'.') 
        self.canvas.draw() 

另一个(可能的)问题是数据被附加到图中而不是被替换。有两种方法可以解决此问题:

  1. 关闭 hold:self.ax.hold(False) 在绘制任何内容之前,在 __init__() 中的某处。
  2. 实际替换绘图数据:替换线条

    self.line, = self.ax.plot(tft[self.event_num],tf1[self.event_num],'.') 
    

    与

    self.line.set_xdata(tft[self.event_num]) 
    self.line.set_ydata(tf1[self.event_num])