2017-03-22 69 views
1

您可以看看這個Tkinter代碼,並讓我知道爲什麼我無法將值插入正確的列嗎?在Tkinter TreeView中插入數據糾正列的問題

正如您從附加圖像中看到的,它似乎將空字符串添加到第一列!

from Tkinter import * 
import ttk 

root = Tk() 

tree = ttk.Treeview(root, columns=('Impacted Features')) 
tree.heading('#0', text='Feature Class') 
tree.heading('#1', text='Impacted Features') 
tree.column('#0', width=100) 
tree.column('#1', width=160) 

tree.grid(row=4, columnspan=6, sticky='nsew') 
tree.insert("",0, values=("1A","1b")) 

root.mainloop() 

enter image description here

回答

1

通過編碼:

tree = ttk.Treeview(root, columns=('Impacted Features'))

你只創建一個列。

tree.insert("",0, values=("1A","1b")) 

所以Tkinter的而沒有空的標題創建一個額外的列:

在你的程序之後,你,如果你有兩列插入數據。這正是你的第一個屏幕截圖顯示的內容。

那麼你能做些什麼來設計你在第二個截圖中突出顯示的GUI?下面是答案:

  • 步驟一:

創建兩列:

tree = ttk.Treeview(root, columns=('zero', 'one')) 

請注意,我選擇了更好的符號名的列。這將導致你用正確的標題,以顯示所需的列中的數據:

enter image description here

  • 第二步:

但你可以看到,有這個GUI問題:空的空間看起來很醜。因此,要擺脫它,你需要依靠show選項:

tree['show'] = 'headings' 

這將導致的結果您正在尋找:

enter image description here

  • 步驟三:

在Python中,一切都是一個對象,所以讓我重新設計您的程序,以便您可以按比例縮放它:

import Tkinter as Tk 
import ttk 


class TreeViewDemo(Tk.Frame): 

    def __init__(self, master): 
     Tk.Frame.__init__(self, master) 
     self.master = master 
     self.master.title("Tree View Demo")  
     # The following 2 lings will expand the widgets as window resizes 
     # Can be removed if the effect is not desired 
     self.master.grid_rowconfigure(0,weight=1) 
     self.master.grid_columnconfigure(0,weight=1) 

     self.create_GUI() 

    def create_GUI(self): 
     self.tree = ttk.Treeview(self.master, columns=('zero', 'one')) 
     self.tree.heading('zero', text='Feature Class') 
     self.tree.heading('one', text='Impacted Features') 
     self.tree.column('zero') 
     self.tree.column('one') 
     self.tree.grid(row=0, column=0, sticky='nsew') 
     self.tree['show'] = 'headings' 
     self.tree.insert('', '0', values=("1A","1b")) 


def main(): 
    root=Tk.Tk() 
    d = TreeViewDemo(root) 
    root.mainloop() 

if __name__ == '__main__': 
    main() 
1

變化tree.insert("",0, values=("1A","1b"))tree.insert("",0, text="1A", values=("1b"))

第一列或icon柱(索引#0)開text和所有其他列採取values

全碼:

from Tkinter import * 
import ttk 

root = Tk() 

tree = ttk.Treeview(root, columns=('Impacted Features')) 
tree.heading('#0', text='Feature Class') 
tree.heading('#1', text='Impacted Features') 
tree.column('#0', width=100) 
tree.column('#1', width=160) 

tree.grid(row=4, columnspan=6, sticky='nsew') 
tree.insert("",0, text="1A", values=("1b")) 

root.mainloop()