如何在.txt文件中保存鼠标事件(实例),然后再次将其打开为intance

时间:2017-03-21 14:26:05

标签: python python-2.7

我有一个onclick函数,它接受self和event(事件是类型实例)所以我可以将这个事件保存在xml或.txt文件中,这样我可以通过浏览按钮再次打开它作为事件实例并将其还给到这个add_point函数

   def add_point(self, event):
    if self.radioButton.isChecked() == True:
        if ((event.xdata)**2 + (event.ydata)**2)**0.5 < 1 and event.ydata >0 :
            print(type(event))
            print (event)

            z = event.xdata + event.ydata * 1j


            self.xy.append([event.xdata, event.ydata])
            self.xy.append([event.xdata, -event.ydata])
            self.zero.append(z)
            print (self.zero)
            self.update()

def浏览(自我):

    filepath = QtGui.QFileDialog.getOpenFileName(self, 'Single File', "C:\Users\Hanna Nabil\Documents",'*.txt')
    f= str(filepath)
    file =open(filepath ,'r')
    connect = self.fig.canvas.mpl_connect
    connect('button_press_event', self.on_click)
    self.draw_cid = connect('draw_event', self.grab_background)
    with file:
        text= file.read()

        #self.add_point(c)
        print(text)

1 个答案:

答案 0 :(得分:0)

我认为您要保存event实例并稍后重新加载。您可以使用pickle包。

import pickle

'''
    To store the instance
'''

path = 'path where do you want to store the event'

output = open(path,'wb')    # Open a file to store the instance binary (your event)

pickle.dump(self.binario, output)    # Dumping the instance binary to the file

output.close()    # Closing the file        


'''
    To load the instance
'''    

input = open(path,'rb')    # Open the file    

event = pickle.load(input)    # Loading the instance binary

input.close()    # Closing the file

event变量是您之前存储的变量,您可以将它用于您的目的。

pickle包的一般用途是存储二进制文件,如实例或类,稍后在同一代码或另一个项目中重新加载。