【问题标题】:How to create new toplevel window with treeview object?如何使用树视图对象创建新的顶层窗口?
【发布时间】:2021-12-05 19:45:17
【问题描述】:

我无法弄清楚为什么这段代码不起作用。单击按钮后,我试图在新的顶层窗口中创建树视图。但是当我向树视图添加滚动条时 - 树视图消失(我用滚动条评论部分)。这是代码:

from tkinter import*
class Treeview(Toplevel):
    def __init__(self, parent):
        super().__init__(parent)
        self.title('Contacts List')
        self.geometry('1050x527')
        columns = ('#1', '#2', '#3', '#4', '#5')
        self = ttk.Treeview(self, columns=columns, show='headings')
        self.heading('#1', text='Name')
        self.heading('#2', text='Birthday')
        self.heading('#3', text='Email')
        self.heading('#4', text='Number')
        self.heading('#5', text='Notes')
        self.grid(row=0, column=0, sticky='nsew')
        #scrollbar = ttk.Scrollbar(self, orient=VERTICAL, command=self.yview)
        #self.configure(yscroll=scrollbar.set)
        #scrollbar.grid(row=0, column=1, sticky='ns')
    root = Tk()
    def tree():
        new= Treeview(root)
    button7 = ttk.Button(root,text="Contacts", command=tree)
    button7.grid(row=1,column=0)
    root.mainloop()

【问题讨论】:

  • 您的代码中似乎存在缩进问题。您在__init__ 中定义root
  • 另外,您从未真正对新的 Treeview 进行网格化。您是否尝试过使用 new.grid 来网格化新的 Treeview?您也将selfToplevel 更改为Treeview,您绝对不应该这样做。与其将self 更改为Treeview,不如为其创建一个变量,例如self.treeview = ttk.Treeview(...
  • 好的,但是我该如何解决呢?或者也许我怎样才能用不同的方式创建顶层窗口?
  • 你想通过重新定义self来达到什么目的?
  • 我不知道我是 tkinter 和 treeview 的新手。

标签: python oop tkinter treeview toplevel


【解决方案1】:

您将self 重新定义为ttk.Treeview 实例。稍后,当您创建滚动条时,这会导致滚动条成为 ttk.Treeview 小部件的子级。

你绝对不应该重新定义self。使用不同的变量,例如tree。或者更好的是,使用self.tree,以便您可以从其他方法引用树。

class Treeview(Toplevel):
    def __init__(self, parent):
        super().__init__(parent)
        self.title('Contacts List')
        self.geometry('1050x527')
        columns = ('#1', '#2', '#3', '#4', '#5')
        self.tree = ttk.Treeview(self, columns=columns, show='headings')
        self.tree.heading('#1', text='Name')
        self.tree.heading('#2', text='Birthday')
        self.tree.heading('#3', text='Email')
        self.tree.heading('#4', text='Number')
        self.tree.heading('#5', text='Notes')
        self.tree.grid(row=0, column=0, sticky='nsew')
        scrollbar = ttk.Scrollbar(self, orient=VERTICAL, command=self.tree.yview)
        self.tree.configure(yscroll=scrollbar.set)
        scrollbar.grid(row=0, column=1, sticky='ns')

【讨论】:

  • 好的,谢谢,这是像我一样创建树视图的好方法吗?还是有更好的方法?
  • @GGGGGG 好吧,不鼓励通配符导入(所以尽量避免使用from tkinter import *)。如果你想在课堂上的其他地方引用树视图,我建议使用self.treeview 而不是简单的treeview。这使您可以在类的任何方法中使用树视图。
  • @SylvesterKruin 你的意思是使用 self.treeview 而不是树?因为 treeview 在他的解决方案中不是变量。
  • @GGGGGG 我的错。不过,同样的原则仍然适用:您可以使用self.tree 而不是tree。使用self. 确保变量可以在整个类中使用
  • @SylvesterKruin:感谢您指出这一点。我已将示例修改为使用 self.tree 而不是 tree
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-05
  • 1970-01-01
  • 1970-01-01
  • 2021-04-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多