2014-10-06 33 views
2

這裏文本長度更大的是一些簡單的代碼:創建滾動條,只有當超過文本區域

from tkinter import * 
from tkinter import ttk 

rootwin = Tk() 

roomtext = Text(rootwin) 
roomtext.pack(side = 'left', fill = "both", expand = True) 

rtas = ttk.Scrollbar(roomtext, orient = "vertical", command = roomtext.yview) 
rtas.pack(side = "right" , fill = "both") 

roomtext.config(yscrollcommand = rtas.set) 

rootwin.mainloop() 

因此,默認scrollbar出現立竿見影。 輸入文本大於文本區域時,如何才能使scrollbar顯示?

所以當我運行代碼時,首先,scrollbar一定不能顯示。然後當輸入足夠的文本時scrollbar顯示(即roomtext中的文本長於roomtext區域)。

+0

最好是與OOP使用Tkinter的。個人從未使用過這樣的tkinter。尋找'root.geometry()'。你可以像'root.geometry(「500x600」)''這樣的字符串傳遞窗口的尺寸。這將允許你有一個足夠大的窗口以適合你的東西。 – Beginner 2014-10-07 00:24:35

+0

是的,我這樣做。如果它隱藏在第一,它的美麗首先看。 – somename 2014-10-07 10:43:05

回答

1

也許這個代碼是你在找什麼(變化的包到網格,我更熟悉它......你應該能夠恢復,很容易,如果你想):

from tkinter import * 
from tkinter import ttk 

rootwin = Tk() 

roomtext = Text(rootwin) 
roomtext.grid(column=0, row=0) 

def create_scrollbar(): 
    if roomtext.cget('height') < int(roomtext.index('end-1c').split('.')[0]): 
     rtas = ttk.Scrollbar(rootwin, orient = "vertical", command = roomtext.yview) 
     rtas.grid(column=1, row=0, sticky=N+S) 
     roomtext.config(yscrollcommand = rtas.set) 
    else: 
     rootwin.after(100, create_scrollbar) 

create_scrollbar() 
rootwin.mainloop() 

它檢查是否需要每秒創建一次滾動條10次。 只需增加一些變化,你甚至可以讓它刪除滾動條在不再需要時(文字太短):

from tkinter import * 
from tkinter import ttk 

rootwin = Tk() 

roomtext = Text(rootwin) 
roomtext.grid(column=0, row=0) 

rtas = ttk.Scrollbar(rootwin, orient = "vertical", command = roomtext.yview) 

def show_scrollbar(): 
    if roomtext.cget('height') < int(roomtext.index('end-1c').split('.')[0]): 
     rtas.grid(column=1, row=0, sticky=N+S) 
     roomtext.config(yscrollcommand = rtas.set) 
     rootwin.after(100, hide_scrollbar) 
    else: 
     rootwin.after(100, show_scrollbar) 

def hide_scrollbar(): 
    if roomtext.cget('height') >= int(roomtext.index('end-1c').split('.')[0]): 
     rtas.grid_forget() 
     roomtext.config(yscrollcommand = None) 
     rootwin.after(100, show_scrollbar) 
    else: 
     rootwin.after(100, hide_scrollbar) 

show_scrollbar() 
rootwin.mainloop() 
+0

謝謝。 也許沒有更好的做到這一點。 – somename 2014-10-09 21:22:17