Skip to main content
 首页 » 编程设计

python之仅当文本长度大于文本区域时才创建滚动条

2024年10月25日9bonelee

下面是一些简单的代码:

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 不能显示。然后,当输入足够的文本时,滚动条 显示(即 roomtext 中的文本比 roomtext 区域长)。

请您参考如下方法:

也许这段代码就是您正在寻找的代码(将 pack 更改为 grid,因为我更熟悉它......如果您愿意,您应该能够轻松地恢复它):

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()