带有水平和垂直滚动条的GUI表(水平无法正常工作)

时间:2019-03-31 13:46:03

标签: python-3.x tkinter

我正在使用python进行分配,但是水平滚动条无法正常工作,垂直滚动条不在适当的位置。

我已经在python中使用水平和垂直滚动条制作了一个n×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

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

1 个答案:

答案 0 :(得分:1)

对于 vsb

  • 它必须粘贴在列的最右端,即使用 sticky =“ nse” ;或在“ frame_canvas”中添加另一列
  • 如果上述方法无效,请为vsb使用选项“ rowspan”

对于 hsb

  • 删除canvas.xview之后的括号
  • 此外,使用 sticky =“ swe”