Tkinter列表框宽度会干扰滚动条

时间:2017-04-26 03:28:59

标签: python tkinter listbox scrollbars

我遇到了一个问题,我有一个滚动条显示几行,每行约200个字符宽。我的宽度设置为125,这还不够。然而,当我碰到它大约175时,我的滚动条消失了。如果我将其设置为100或低于100,则滚动浏览所有数据,但这是一个非常小的窗口。我希望窗口是框架的大小,并滚动所有代码。 代码:

import Tkinter as tk
import tkFont
def view():
    data = ['|unique_id |     id |              species | sex_age |  collector |                          location |                  preparator | collection_date | entered_date | innitials |         notes', 
            '|       88 | A-1444 |      puffinus grseus |     n/a |        n/a |                               n/a |                         n/a |     13 May 2013 |  27 Apr 2017 |        EB | TL: 395mm WC:',
            '|       72 | A-1444 |      puffinus grseus |     n/a |        n/a |                               n/a |                         n/a |     13 May 2013 |  27 Apr 2017 |        EB | TL: 395mm WC:',
            '|       71 | A-1445 |        anas clypeata |       M |  G. Webber |                               n/a |                     A. Zack |     23 Oct 2013 |  26 Apr 2017 |        EB | TL: 395mm WC:',
            '|       87 | A-1445 |        anas clypeata |       M |  G. Webber |                               n/a |                     A. Zack |     23 Oct 2013 |  26 Apr 2017 |        EB | TL: 395mm WC:']
    size = [800, 600]
    obj_main_frame = tk.Tk()
    data_frame = tk.Frame(obj_main_frame, width=size[0], height=size[1])
    scrollbar_y = tk.Scrollbar(obj_main_frame, orient=tk.VERTICAL)
    scrollbar_x = tk.Scrollbar(obj_main_frame, orient=tk.HORIZONTAL)
    data_scrollable = tk.Listbox(data_frame, font=tkFont.Font(family="Courier", size=10), selectbackground="gray", selectmode=tk.SINGLE, width=150, yscrollcommand=scrollbar_y.set, xscrollcommand=scrollbar_x.set)
    scrollbar_y.config(command=data_scrollable.yview)
    scrollbar_x.config(command=data_scrollable.xview)
    obj_main_frame.grid()
    data_frame.grid_propagate(0)
    data_frame.grid(row=0, column=0, sticky='nsew')
    scrollbar_x.grid(row=1, column=0, sticky='ew')
    scrollbar_y.grid(row=0, column=1, sticky='ns')
    data_scrollable.grid(row=0, column=0, sticky='nsew')
    for i, datum in enumerate(data):
        data_scrollable.insert(tk.END, datum)

    obj_main_frame.mainloop()
    return

if __name__ == '__main__':
    view()

1 个答案:

答案 0 :(得分:1)

你在对齐中犯了2个错误。

  • 首先,您应该在定义列表框时删除width参数,以便它可以调整为其父级的大小:

    data_scrollable = tk.Listbox(data_frame, 
                                 font=tkFont.Font(family="Courier", size=10),
                                 selectbackground="gray", selectmode=tk.SINGLE,
                                 yscrollcommand=scrollbar_y.set,
                                 xscrollcommand=scrollbar_x.set)
    
  • 其次,在将列表框对齐到其框架中之后,必须为相应的行和列提供非零权重,以允许列表框展开:

    data_scrollable.grid(row=0, column=0, sticky='nsew')
    data_frame.columnconfigure(0, weight=1)
    data_frame.rowconfigure(0, weight=1)
    

请参阅:Tkinter Grid Manager documentation