Tkinter的;在画布中使用滚动条

时间:2012-06-28 20:33:27

标签: tkinter scrollbar frame tkinter-canvas

我正在尝试在程序的一部分中创建滚动条。父框架有三个标签框架小部件,其中一个需要显示多达50个选项菜单,使滚动条成为可取。

我知道你不能使用滚动条滚动标签框架,所以在这个标签框架内我创建了一个可以滚动的画布。然后我在画布中插入了一个框架,我将用它来显示选项菜单。然后我将滚动条附加到画布上,滚动条放在标签框内。问题是滚动条看起来很实用,但只有前10个选项菜单是可见的,无论它滚动多少。以下是一个例子:

from Tkinter import *

app = Tk()
app.title("Example App")
app.geometry("550x400+300+300")

# Creating the first label frame
entryframe = LabelFrame(app,text="Entry",width=250,height=250)
entryframe.pack(side="top",fill=BOTH)

# Creating a frame to contain the options selected by the user; also using a canvas & 
# label frame to enable the use of a scrollbar
outcomesframe = LabelFrame(app,text="User Input",width=250,height=650)
outcomesframe.pack(side="left",fill=BOTH)
outcomescanvas = Canvas(outcomesframe,relief=SUNKEN)
outcomescanvas.config(width=230,height=650)
outcomescanvas.config(scrollregion=(0,0,300,1000))
outcomescanvas.config(highlightthickness=0)

# Creating scrollbar
scrollbar = Scrollbar(outcomesframe)
scrollbar.config(command=outcomescanvas.yview)
outcomescanvas.config(yscrollcommand=scrollbar.set)
scrollbar.pack(side="right",fill=Y)
outcomescanvas.pack(side="left",expand=YES,fill=BOTH)

# Creating the frame in which the option menus will be inserted
outcomesframe2 = Frame(outcomescanvas,width=230,height=1000)
outcomesframe2.pack(side="top",fill=BOTH)

# Creating the third label frame
statsframe = LabelFrame(app,text="Third Label Frame",width=250,height=250)
statsframe.pack(side="right",fill=BOTH)

# Creating the option menus
for i in range(50):
    vars()["labeltext"+str(i)] = StringVar()
    vars()["labeltext"+str(i)].set("Menu"+str(i+1)+":")
    vars()["label"+str(i)] = Label(outcomesframe2,textvariable=vars()["labeltext"+str(i)])
    vars()["label"+str(i)].grid(row=i,column=0)

    vars()["variable"+str(i)] = StringVar()
    vars()["variable"+str(i)].set("Select...")
    vars()["menu"+str(i)] = OptionMenu(outcomesframe2,vars()["variable"+str(i)],"Option1","Option2")
    vars()["menu"+str(i)].pack()

app.mainloop()

1 个答案:

答案 0 :(得分:0)

滚动画布时,它仅滚动作为画布对象的项目。这意味着您必须使用create_window在画布中放置一个窗口,而不是使用packgrid

...
outcomescanvas.create_window(0,0,window=outcomesframe2, anchor="nw")
...