Creating a table look-a-like Tkinter

前端 未结 3 2148
天涯浪人
天涯浪人 2020-11-27 17:36

I am looking to create something that resembles a table in Tkinter but it doesn\'t necessarily have to be one.

I would like to create headers \'Name1\', \'Name2\', \

3条回答
  •  眼角桃花
    2020-11-27 18:29

    What problem are you having? The simple solution is to lay out widgets using grid. You can put whatever type of widget you want in each cell. And yes, labels can have borders. Though, a simple way to do grid lines is to use a padding around each cell, so that the color of the frame will show through the gaps.

    Do this in a frame. If you need to be able to scroll the table, put the frame inside a canvas and add scrollbars. There are examples all over the web for how to create a scrollable frame using a canvas.

    Here's a really quick example that uses just labels, and doesn't scroll. I'll leave the exact implementation of what you need as an exercise for the reader.

    import Tkinter as tk
    
    class ExampleApp(tk.Tk):
        def __init__(self):
            tk.Tk.__init__(self)
            t = SimpleTable(self, 10,2)
            t.pack(side="top", fill="x")
            t.set(0,0,"Hello, world")
    
    class SimpleTable(tk.Frame):
        def __init__(self, parent, rows=10, columns=2):
            # use black background so it "peeks through" to 
            # form grid lines
            tk.Frame.__init__(self, parent, background="black")
            self._widgets = []
            for row in range(rows):
                current_row = []
                for column in range(columns):
                    label = tk.Label(self, text="%s/%s" % (row, column), 
                                     borderwidth=0, width=10)
                    label.grid(row=row, column=column, sticky="nsew", padx=1, pady=1)
                    current_row.append(label)
                self._widgets.append(current_row)
    
            for column in range(columns):
                self.grid_columnconfigure(column, weight=1)
    
    
        def set(self, row, column, value):
            widget = self._widgets[row][column]
            widget.configure(text=value)
    
    if __name__ == "__main__":
        app = ExampleApp()
        app.mainloop()
    

提交回复
热议问题