如何在Tkinter中创建带滚动条的Frame?
我想要一个Frame
,用户可以根据应用的需要添加任意数量的文本框。
这个应用一开始会有一个文本框,下面有一个按钮。当用户点击这个按钮时,会在第一个文本框下面添加一个新的文本框(这个过程可以重复很多次)。在窗口的中间,会有一个Text
小部件,用来显示文本 :)
不过,我在文档中注意到这一点:
这个小部件用于实现可滚动的列表框、画布和文本框。
有没有办法在Frame
中使用Scrollbar
?
2 个回答
7
下面是一个关于自动隐藏滚动条的例子,这个例子只有在你使用网格布局管理器时才有效,内容来自于effbot.org
的文档:
from tkinter import *
class AutoScrollbar(Scrollbar):
# A scrollbar that hides itself if it's not needed.
# Only works if you use the grid geometry manager!
def set(self, lo, hi):
if float(lo) <= 0.0 and float(hi) >= 1.0:
# grid_remove is currently missing from Tkinter!
self.tk.call("grid", "remove", self)
else:
self.grid()
Scrollbar.set(self, lo, hi)
def pack(self, **kw):
raise TclError("cannot use pack with this widget")
def place(self, **kw):
raise TclError("cannot use place with this widget")
# create scrolled canvas
root = Tk()
vscrollbar = AutoScrollbar(root)
vscrollbar.grid(row=0, column=1, sticky=N+S)
hscrollbar = AutoScrollbar(root, orient=HORIZONTAL)
hscrollbar.grid(row=1, column=0, sticky=E+W)
canvas = Canvas(root, yscrollcommand=vscrollbar.set, xscrollcommand=hscrollbar.set)
canvas.grid(row=0, column=0, sticky=N+S+E+W)
vscrollbar.config(command=canvas.yview)
hscrollbar.config(command=canvas.xview)
# make the canvas expandable
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
# create canvas contents
frame = Frame(canvas)
frame.rowconfigure(1, weight=1)
frame.columnconfigure(1, weight=1)
rows = 5
for i in range(1, rows):
for j in range(1, 10):
button = Button(frame, text="%d, %d" % (i,j))
button.grid(row=i, column=j, sticky='news')
canvas.create_window(0, 0, anchor=NW, window=frame)
frame.update_idletasks()
canvas.config(scrollregion=canvas.bbox("all"))
root.mainloop()
8
如果你能使用Tix库的话,可以用一个叫做ScrolledWindow的控件。这个控件里面有一个window
框架和一个或两个滚动条控件:
import Tix as tk
r= tk.Tk()
r.title("test scrolled window")
sw= tk.ScrolledWindow(r, scrollbar=tk.Y) # just the vertical scrollbar
sw.pack(fill=tk.BOTH, expand=1)
for i in xrange(10):
e= tk.Entry(sw.window)
e.pack()
r.mainloop()
你需要调整根窗口的大小。你还需要在Entry控件的focus_get事件中添加代码,这样在用键盘切换时,ScrolledWindow就会自动滚动。
如果不这样做,你就得使用一个Canvas控件(你可以在里面添加Label、Entry和Text等子控件),而且需要自己写更多的代码来实现你想要的功能。