如何将数据框数据填充到网格条目 tkinter

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

我想分享我的将测试数据填充到网格条目中的代码。但是,我正在寻求帮助以将我的 DataFrame 数据用于此目的。我当前的实现使用原始 DataFrame 来填充网格条目,但遇到了错误。如何在网格条目中有效地使用我的 DataFrame 数据?

import tkinter as tk
import pandas as pd
#import tkinter

class ResizableGrid(tk.Frame):
    def __init__(self, parent, rows, columns, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)

        self.rows = rows
        self.columns = columns

        self.entry_grid = [[tk.Entry(self) for _ in range(columns)] for _ in range(rows)]
        self.configure_grid()   # it give error 

        self.bind_mouse()

    def configure_grid(self):
        df = pd.read_excel('c:/erp/book11.xlsx',header=None)
        #for i, row in df.iterrows():    # run ok 
         #      c = 0
        #for cell in row:
         #       tk.Label(root, text=cell).grid(row=i, column=c)    # run ok fill my df data into lable 
          #      c += 1
        
        
        #for i in range(self.rows):
        for i, row in df.iterrows():
         #   for j in range(self.columns):   3 it run gine with out error with testing data 
                j = 0
        for  cell in row:    # it give the error 
                self.entry_grid[i][j].grid(row=i, column=j, sticky="nsew", padx=1, pady=1)  # it give error when use dataframe 
                #self.entry_grid[i][j].insert(0, 'testing')   # it run fine
                self.entry_grid[i][j].insert(0, cell)   # it give error 
                if i==3 and j==0:self.entry_grid[i][j].config(bg = "green") 
                #if i==3 and j==0:self.entry_grid[i][j].config(bg = "green",width=100) 
                self.entry_grid[i][j].bind("<Enter>", lambda event, col=j: self.on_enter(event, col))
                j += 1




        for i in range(self.rows):
            self.grid_rowconfigure(i, weight=1)

        for j in range(self.columns):
            self.grid_columnconfigure(j, weight=1)

    def bind_mouse(self):
        self.bind("<B1-Motion>", self.on_motion)
        self.bind("<ButtonRelease-1>", self.on_release)

    def on_enter(self, event, col):
        self.current_column = col

    def on_motion(self, event):
        if hasattr(self, "current_column"):
            col = self.current_column
            width = event.x - self.entry_grid[0][col].winfo_x()
            self.columnconfigure(col, minsize=max(50, width))

    def on_release(self, event):
        if hasattr(self, "current_column"):
            delattr(self, "current_column")

if __name__ == "__main__":
    root = tk.Tk()
    root.title("Resizable Grid")

    rows = 5
    columns = 8

    grid = ResizableGrid(root, rows, columns)
    grid.pack(expand=True, fill="both")

    #button5= tk.Button(root, text="Muhammad")
    #button5.grid(row=2,column=2)
    root.mainloop()
File "c:\mainfol\mfatt\11024gridcolumnriszing.py", line 13, in __init__
    self.configure_grid()   # it give error
    ^^^^^^^^^^^^^^^^^^^^^
  File "c:\mainfol\mfatt\11024gridcolumnriszing.py", line 32, in configure_grid
    self.entry_grid[i][j].grid(row=i, column=j, sticky="nsew", padx=1, pady=1)  # it give error when use dataframe 
    ~~~~~~~~~~~~~~~~~~^^^
IndexError: list index out of range
python tkinter
1个回答
0
投票

我假设你犯了错误

rows = 5
columns = 8

像这样删除数字是不好的做法,我实现了一种方法,可以直接从数据集中获取行和列值:

import tkinter as tk
import pandas as pd
#import tkinter

class ResizableGrid(tk.Frame):
    def __init__(self, parent, path_df, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.df = pd.read_excel(path_df,header=None)
        
        self.rows = self.df.count()[0] #get row len
        self.columns = len(self.df.columns)  #get col len

        self.entry_grid = [[tk.Entry(self) for _ in range(self.columns)] for _ in range(self.rows)]
        self.configure_grid()   # it give error 

        self.bind_mouse()

    def configure_grid(self):
        
        #for i, row in df.iterrows():    # run ok 
         #      c = 0
        #for cell in row:
         #       tk.Label(root, text=cell).grid(row=i, column=c)    # run ok fill my df data into lable 
          #      c += 1
        
 
        #for i in range(self.rows):
        for i, row in self.df.iterrows():
         #   for j in range(self.columns):   3 it run gine with out error with testing data 
            j = 0
            
            for cell in row:    # it give the error 
                self.entry_grid[i][j].grid(row=i, column=j, sticky="nsew", padx=1, pady=1)  # it give error when use dataframe 
                #self.entry_grid[i][j].insert(0, 'testing')   # it run fine
                self.entry_grid[i][j].insert(0, cell)   # it give error 
                if i==3 and j==0:self.entry_grid[i][j].config(bg = "green") 
                #if i==3 and j==0:self.entry_grid[i][j].config(bg = "green",width=100) 
        
                self.entry_grid[i][j].bind("<Enter>", lambda event, col=j: self.on_enter(event, col))
                j += 1




        for i in range(self.rows):
            self.grid_rowconfigure(i, weight=1)

        for j in range(self.columns):
            self.grid_columnconfigure(j, weight=1)

    def bind_mouse(self):
        self.bind("<B1-Motion>", self.on_motion)
        self.bind("<ButtonRelease-1>", self.on_release)

    def on_enter(self, event, col):
        self.current_column = col

    def on_motion(self, event):
        if hasattr(self, "current_column"):
            col = self.current_column
            width = event.x - self.entry_grid[0][col].winfo_x()
            self.columnconfigure(col, minsize=max(50, width))

    def on_release(self, event):
        if hasattr(self, "current_column"):
            delattr(self, "current_column")

if __name__ == "__main__":
    root = tk.Tk()
    root.title("Resizable Grid")

    grid = ResizableGrid(root,r"c:/erp/book11.xlsx"  )
    grid.pack(expand=True, fill="both")

    #button5= tk.Button(root, text="Muhammad")
    #button5.grid(row=2,column=2)
    root.mainloop()

这段代码对我使用 96x2 数据框有效。

如果需要进一步帮助,请随时告诉我!

© www.soinside.com 2019 - 2024. All rights reserved.