2013-07-15 38 views
11

下面的代碼產生了一個在文本小部件中使用滾動條的醜陋但功能性示例,併產生了一些問題。注意:這是通過在Windows窗口上使用Python 3完成的。如何對tkinter「scrolledtext」模塊進行編碼

  1. 出現連接到框架,儘管它滾動文本框內容,我寧願它被附加到文本組件本身的滾動條。我一直無法做到這一點。

  2. 有一些Tkinter模塊的引用稱爲「滾動文本」,應該是一個更好的機制,用於向文本框添加滾動條,但是我還沒有找到任何有關如何導入它並調用它的示例我可以開始工作(可能需要一個例子)。


frame1 = tk.Frame(win,width=80, height=80,bg = '#808000') 
frame1.pack(fill='both', expand='yes') 
scrollbar = Scrollbar(frame1) 
scrollbar.pack(side=RIGHT, fill=Y) 
editArea = Text(frame1, width=10, height=10, wrap=WORD, yscrollcommand=scrollbar.set) 
editArea.pack()  
scrollbar.config(command=editArea.yview) 
editArea.place(x=10,y=30) 

回答

20

你是對的,你可以使用ScrolledText部件從tkinter.scrolledtext模塊,像這樣:

import tkinter as tk 
import tkinter.scrolledtext as tkst 

win = tk.Tk() 
frame1 = tk.Frame(
    master = win, 
    bg = '#808000' 
) 
frame1.pack(fill='both', expand='yes') 
editArea = tkst.ScrolledText(
    master = frame1, 
    wrap = tk.WORD, 
    width = 20, 
    height = 10 
) 
# Don't use widget.place(), use pack or grid instead, since 
# They behave better on scaling the window -- and you don't 
# have to calculate it manually! 
editArea.pack(padx=10, pady=10, fill=tk.BOTH, expand=True) 
# Adding some text, to see if scroll is working as we expect it 
editArea.insert(tk.INSERT, 
"""\ 
Integer posuere erat a ante venenatis dapibus. 
Posuere velit aliquet. 
Aenean eu leo quam. Pellentesque ornare sem. 
Lacinia quam venenatis vestibulum. 
Nulla vitae elit libero, a pharetra augue. 
Cum sociis natoque penatibus et magnis dis. 
Parturient montes, nascetur ridiculus mus. 
""") 
win.mainloop() 

而且你去:

enter image description here

9

雖然使用ScrolledText小部件可能會爲您節省幾行代碼,但它不會做任何您無法做到的事情。自己做,將有助於消除一些謎團。

你實際上做的一切幾乎都是正確的。你所犯的錯誤是你應該讓你的文本小部件完全填充它的容器,而不僅僅是它的一小部分。

標準的方式來做到這一點是這樣的:

container = tk.Frame(...) 
text = tk.Text(container, ...) 
scrollbar = tk.Scrollbar(container, ...) 
scrollbar.pack(side="right", fill="y") 
text.pack(side="left", fill="both", expand=True) 

這一切就是這麼簡單。現在,無論您的容器因窗口大小等原因而變得多大,滾動條將始終顯示爲附加到文本窗口小部件。然後,將整組容器,文本小部件和滾動條作爲單個小部件添加到整個GUI中。

請注意,您也可以在此處使用網格。如果您只有一個垂直滾動條,則打包更容易。如果你有水平和垂直滾動條,網格會更有意義。

爲了完成幻覺,您可以將文本窗口小部件的邊框寬度設置爲零,並將包含窗口的邊框寬度設置爲1,同時消除凹陷,並且滾動條將顯示爲位於文本窗口小部件中。

這是一個完整的工作示例,看起來更多或更少喜歡你的例子:

import Tkinter as tk 

win = tk.Tk() 

win.configure(background="#808000") 

frame1 = tk.Frame(win,width=80, height=80,bg = '#ffffff', 
        borderwidth=1, relief="sunken") 
scrollbar = tk.Scrollbar(frame1) 
editArea = tk.Text(frame1, width=10, height=10, wrap="word", 
        yscrollcommand=scrollbar.set, 
        borderwidth=0, highlightthickness=0) 
scrollbar.config(command=editArea.yview) 
scrollbar.pack(side="right", fill="y") 
editArea.pack(side="left", fill="both", expand=True) 
frame1.place(x=10,y=30) 

win.mainloop() 

我個人不建議這樣做全球進口的,我不建議使用的地方,但我想盡可能使其儘可能接近您的原稿。