Tkinter干净地显示varLabel和值

时间:2012-09-09 03:27:41

标签: python tkinter

我是Tkinter的新手,并编写了一个程序来打开文件并解析二进制消息。

我正在努力研究如何最好地显示结果。我的解析类将有300多个条目,我想要一个类似于表的东西。

var1Label : var1Val

var2Label : var2Val

我玩过这些小部件,但没有得到任何让我感到自豪的东西:标签,文字,短信和其他可能。

所以我希望标签是正确的,并且Var是合理的左边或其他任何可能是一个好主意,如何使这个有吸引力的显示,如所有':'对齐。 Var的大小将在0到15个字符之间。

我在Windows上使用python 2.7.2。

这是我尝试使用虚拟变量的网格方法

self.lbVar1 = Label(self.pnDetails1, text="Var Desc:", justify=RIGHT, bd=1)
self.lbVar1.grid(sticky=N+W)
self.sVar1 = StringVar( value = self.binaryParseClass.Var1 )
self.Var1  = Label(self.pnDetails1, textvariable=self.sVar1)
self.Var1.grid(row=0, column=1, sticky=N+E)

1 个答案:

答案 0 :(得分:0)

ttk.Treeview窗口小部件可让您创建包含多列的对象列表。它可能是你最容易使用的东西。

由于您特别询问了标签网格,这里有一个快速而肮脏的示例,展示了如何在可滚动网格中创建300个项目:

import Tkinter as tk
class ExampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)

        # create a canvas to act as a scrollable container for
        # the widgets
        self.container = tk.Canvas(self)
        self.vsb = tk.Scrollbar(self, orient="vertical", command=self.container.yview)
        self.container.configure(yscrollcommand=self.vsb.set)
        self.vsb.pack(side="right", fill="y")
        self.container.pack(side="left", fill="both", expand=True)

        # the frame will contain the grid of labels and values
        self.frame = tk.Frame(self)
        self.container.create_window(0,0, anchor="nw", window=self.frame)

        self.vars = []
        for i in range(1,301):
            self.vars.append(tk.StringVar(value="This is the value for item %s" % i))
            label = tk.Label(self.frame, text="Item %s:" % i, width=12, anchor="e")
            value = tk.Label(self.frame, textvariable=self.vars[-1], anchor="w")
            label.grid(row=i, column=0, sticky="e")
            value.grid(row=i, column=1, sticky="ew")

        # have the second column expand to take any extra width
        self.frame.grid_columnconfigure(1, weight=1)

        # Let the display draw itself, the configure the scroll region
        # so that the scrollbars are the proper height
        self.update_idletasks()
        self.container.configure(scrollregion=self.container.bbox("all"))

if __name__ == "__main__":
    app = ExampleApp()
    app.mainloop()