老板
我观察到我的代码执行正确并成功调整了网格列的大小;然而,该牢房仍然无人居住。我想使用数据库、Excel 文件或数据框中的数据填充单元格或输入框。此外,我寻求有关如何根据特定行或列号填充单元格的指导。
看我的代码
import tkinter as tk
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,cursor="circle") for _ in range(columns)] for _ in range(rows)]
# self.entry_grid.insert(0, "Hello, world") # how to fill grid entry by my databse data or fill by row and column
# $self.entry_grid.insert(0, rows+colmun)
self.configure_grid()
self.bind_mouse()
def configure_grid(self):
for i in range(self.rows):
for j in range(self.columns):
self.entry_grid[i][j].grid(row=i, column=j,sticky="nsew", padx=1, pady=1)
self.entry_grid[i][j].bind("<Enter>", lambda event, col=j: self.on_enter(event, col))
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")
root.mainloop()
self.entry_grid.insert(0, "Hello, world")
您可以在类中的第 2 行第 3 列处插入类似以下内容:
self.entry_grid[2][3].insert(0, "Hello, world (2,3)")
这里在类外的第 4 行第 5 列中插入一些内容:
grid.entry_grid[4][5].insert(0, "Hello, world (4,5)")