2009-12-09 89 views
8

我想要一个Frame,用户可以根据应用程序的需要添加尽可能多的文本字段。如何在Tkinter中使用滚动条获取框架?

该应用程序以一个文本框和该文本框下的一个按钮开头。当用户按下按钮时,将在第一个下方添加新的文本输入(这可能会重复无数次)。在窗口的中间,会有一个小部件Text,用于显示文字:)

然而,我的文档中注意到了这一点:

This widget is used to implement scrolled listboxes, canvases, and text fields.

是否有使用Scrollbar方式与Frame

回答

8

如果你可以使用蒂克斯,有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子小部件)并自行编写更多代码来实现所需的功能。

6

以下是自动隐藏滚动条如果你只是使用电网几何经理,从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() 
+0

我不认为这个问题是相关的。我刚刚为Windows下载了Python 2.6.6,并附带了Tix。所以,它似乎和Tkinter一样工作。 – 2010-10-06 04:41:44

+0

谢谢!这是一个很大的帮助。 – reckoner 2010-10-07 20:44:29

+0

我试图将此答案中的代码重构为其可重用的'class',但未成功。如果你有时间在这里看看我的问题,我真的很感激它:http://stackoverflow.com/questions/30018148/python-tkinter-frame-class-with-autohiding-scroll-bars另外,Rinzler ,为什么您将此代码作为编辑发布,而不是作为其自身的答案?现在来自2010年的评论现在没有任何意义,而且我从这个代码中获得的代表最终将会被计算在内,而与代码无关。你应该发布一个新的答案,然后回滚你的编辑。 – ArtOfWarfare 2015-05-03 19:25:10