Pass data frame through Tkinter classes

前端 未结 2 2054
长发绾君心
长发绾君心 2021-02-19 00:20

I am using Python 2.7 and Tkinter. I am almost new to Object Oriented programs. I have a long program with many Tkinter windows and at some point I ask the user to load an Excel

2条回答
  •  半阙折子戏
    2021-02-19 00:54

    in my opinion your are tying too much the data and the GUI. What if in the future you want to display something else? I would use a more generic approach: I would a create a DataProvider class that would read and return the data for you:

    Data Provider

    import pandas as pd
    
        class DataProvider(object):
    
            def __init__(self):
                self._excel = {}
                self._binary = {}
    
            def readExcel(self, filename):
                self._excel[filename] = pd.read_excel(filename)
    
            def excel(self):
                return self._excel
    
            def readBinary(self, filename):
                self._binary[filename] = open(filename,"rb").read()
    
            def binary(self):
                return self._binary
    

    Using this class you can obtain the data that you can present in your GUI:

    gui.py

    from Tkinter import *
    from DataProvider import *
    import binascii
    
    #example data
    dp = DataProvider()
    dp.readExcel("file.xlsx")
    dp.readBinary("img.png")
    
    
    root = Tk()
    frame = Frame(root)
    frame.pack()
    
    bottomframe = Frame(root)
    bottomframe.pack( side = BOTTOM )
    
    w = Label(bottomframe, text=dp.excel()["file.xlsx"])
    w.pack()
    
    
    w = Label(bottomframe, text=binascii.hexlify(dp.binary()["img.png"][:5]))
    w.pack()
    
    root.mainloop()
    

    If all works well you should have a small GUI showing the content of the Excel file and the first few bytes of the image.

    Let me know if all works fine or if you need more info.

    Thanks

提交回复
热议问题