我正在Tkinter中创建一个测验,当前正在研究一个框架,以显示我想以“表”格式显示的SQLite数据库中的记录。我已经创建了一组标签,可以用作我的“表格”,但无法成功实现滚动条。
我了解到滚动条不能直接与框架配合使用,因此我需要创建一个画布并将所有小部件附加到该画布上。我试图通过论坛上提供的一些解决方案来工作,但是无法将它们与我自己的代码正确集成。目前,我创建的滚动条不起作用。
class Progress(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.___init__(self, parent)
frametwo = Frame(self) #creates a secondary frame for the canvas?
frametwo.grid(row = 2, column = 0)
#attempts to create a functional scroll bar
text_area = tk.Canvas(frametwo)
vscroll = tk.Scrollbar(text_area, orient="vertical", command = text_area.yview)
text_area['yscrollcommand'] = vscroll.set
text_area.grid(row=2, column=0, sticky=tk.N+tk.S+tk.E+tk.W)
vscroll.grid(row=2, column=6, sticky="nsew")
text_area.configure(scrollregion = text_area.bbox("all"))
#creates the label widgets
self._widgets = []; columns = 6
for row in range(0,11):
current_row = []
for column in range(columns):
label = tk.Label(text_area, text="%s/%s" % (row, column),
borderwidth=0, width=10, height =2 )
label.config(bg = "White", font=("Calibri bold", 20))
label.grid(row =(row+2), column=column, sticky="nsew", padx=1, pady=1)
current_row.append(label)
self._widgets.append(current_row)
for column in range(columns):
self.grid_columnconfigure(column, weight=1)
很抱歉,如果代码不清楚/效率低下,我非常喜欢tkinter的初学者!上面的代码以我想要的方式输出我的标签,并在它们旁边放置一个滚动条,但是它没有任何功能,并且不会移动以显示其余的小部件。我确定我犯了一个基本错误或省略了一些代码。我该如何纠正?
答案 0 :(得分:0)
您需要在canvas
中制作另一个框架,然后使用canvas.create_window
创建框架。标签小部件应放在该框架内。
class Progress(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
frametwo = tk.Frame(self) #creates a secondary frame for the canvas?
frametwo.grid(row = 2, column = 0)
#attempts to create a functional scroll bar
canvas = tk.Canvas(frametwo)
canvas_frame = tk.Frame(canvas)
vscroll = tk.Scrollbar(frametwo, orient="vertical", command = canvas.yview)
canvas['yscrollcommand'] = vscroll.set
canvas.grid(row=2, column=0, sticky=tk.N+tk.S+tk.E+tk.W)
vscroll.grid(row=2, column=6, sticky="nsew")
#creates the label widgets
self._widgets = []; columns = 6
for row in range(0,11):
current_row = []
for column in range(columns):
label = tk.Label(canvas_frame, text="%s/%s" % (row, column),
borderwidth=0, width=10, height =2 )
label.config(bg = "White", font=("Calibri bold", 20))
label.grid(row =(row+2), column=column, sticky="nsew", padx=1, pady=1)
current_row.append(label)
self._widgets.append(current_row)
for column in range(columns):
self.grid_columnconfigure(column, weight=1)
canvas.create_window((0, 0), window=canvas_frame, anchor='nw')
canvas_frame.bind("<Configure>", lambda e: canvas.configure(scrollregion = canvas.bbox("all"),width=450,height=300))