【问题标题】:GUI table with horizontal and vertical scrollbar (horizontal not properly working)带有水平和垂直滚动条的 GUI 表(水平不能正常工作)
【发布时间】:2019-03-31 22:15:57
【问题描述】:

我正在使用 python 为我的作业制作表格,但水平滚动条无法正常工作,垂直滚动条不在适当的位置。

我已经在 python 中制作了一个带有水平和垂直滚动条的 n x m 表。垂直滚动条工作正常,但水平滚动条不正常。表格只显示5列7行,其余列和行可以通过滚动查看。

我的问题是水平滚动条一直延伸到最后一列。假设有 10 列,必须首先显示其中的 5 列,但水平延伸到最后一列。而且,垂直滚动条不在合适的位置。

下面的代码是一个例子。

# Create the Frame canvas
root = Tk()
frame_canvas = Frame(root)
frame_canvas.grid( row=2, column=2, pady=(5, 0), sticky='nw' )
frame_canvas.grid_rowconfigure( 0, weight=1 )
frame_canvas.grid_columnconfigure( 0, weight=1 )

frame_canvas.grid_propagate( False )

# Add a canvas in the frame
canvas = Canvas( frame_canvas)


# Link the scrollbars to the canvas
vsb = Scrollbar( frame_canvas, orient="vertical", command=canvas.yview )
canvas.configure( yscrollcommand=vsb.set )
vsb.grid( row=0, column=2, sticky='ns' )

hsb = Scrollbar(frame_canvas, orient="horizontal", command=canvas.xview())
hsb.grid(row=1, column=2, sticky='we')
canvas.configure( xscrollcommand=hsb.set )

canvas.grid( row=0, column=2, padx=(5, 5), sticky="news" )

# Create a frame to contain the cells of the table
frame_buttons = Frame(canvas)
canvas.create_window( (0, 0), window=frame_buttons, anchor='nw' )

# Add the contents to the table
header = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
prod_rows = 15
prod_col = len(header)
entries = [[Label() for j in xrange( prod_col )] for i in xrange( prod_rows )]

for i in range( 0, prod_rows ):
    if i == 0:
        for j in range( 0, prod_col ):
            entries[i][j] = Label(canvas, text=header[j], width=10 )
            entries[i][j].grid( row=i, column=j, sticky='news' )
    else:
        for j in range( 0, prod_col ):
            entries[i][j] = Label( frame_buttons, text=" ", relief="groove", width=10)  # ("%d,%d" % (i+1, j+1))
            entries[i][j].grid( row=i, column=j, sticky='news' )

# Update cell frames idle tasks to let tkinter calculate buttons sizes
frame_buttons.update_idletasks()

# Resize the canvas frame to show exactly a 5 by 7 table 
columns_width = sum( [entries[0][j].winfo_width() for j in range( 0, 5)] )
rows_height = sum( [entries[i][0].winfo_height() for i in range( 0, 8 )] )
frame_canvas.config( width=columns_width,
                 height=rows_height)     # + 
vsb.winfo_width()

# Set the canvas scrolling region
canvas.config(scrollregion=canvas.bbox( "all" ) )

root.mainloop()

this is an image of the output of the code above

滚动条必须严格位于指定的角落。

【问题讨论】:

    标签: python-3.x tkinter


    【解决方案1】:

    对于vsb

    • 必须贴在列的最右端,即使用sticky = "nse";或向“frame_canvas”添加另一列
    • 如果上述方法不起作用,请为 vsb 使用选项“rowspan”

    对于hsb

    • 去掉canvas.xview后面的括号
    • 另外,使用 sticky = "swe"

    【讨论】:

      猜你喜欢
      • 2016-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-09
      相关资源
      最近更新 更多