【问题标题】:Create scrollbar only when text length greater than text area仅当文本长度大于文本区域时创建滚动条
【发布时间】:2014-12-01 05:56:42
【问题描述】:

下面是一些简单的代码:

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 区域长)。

【问题讨论】:

  • 最好将 tkinter 与 OOP 一起使用。我个人从未像这样使用过 tkinter。寻找root.geometry()。您可以将窗口的尺寸作为root.geometry("500x600") 之类的字符串传递。这将使您有一个足够大的窗口来容纳您的东西。
  • 是的,我这样做。如果它先藏起来,第一眼看上去很漂亮。

标签: python python-3.x tkinter


【解决方案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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多