Tkinter Scrollbar滚动条自动隐藏
   1

Tkinter的滚动条,在数据比较少的时候也展示,看着很不美观。可以通过检测鼠标的事件,当鼠标进入到组件上方时才展示,鼠标移出组件上方时,隐藏。

关键事件,<Enter> 鼠标进入组件上方, <Leave> 鼠标移出组件上方。
关键方法,bar.lift(widget),bar.lower(widget),这两个方法的作用,分别是提高组件层级,和降低组件层级,传入的参数,则表示比传入组件的层级高或更低。类似html样式中的index属性,通过调整层级,实现显示和隐藏滚动条。

代码演示

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from tkinter import *
from tkinter.ttk import *

# 自动隐藏滚动条
def scrollbar_autohide(bar, widget):
    def show():
        bar.lift(widget)

    def hide():
        bar.lower(widget)

    hide()
    widget.bind("<Enter>", lambda e: show())
    bar.bind("<Enter>", lambda e: show())
    widget.bind("<Leave>", lambda e: hide())
    bar.bind("<Leave>", lambda e: hide())


class WinGUI(Tk):
    def __init__(self):
        super().__init__()
        self.__win()
        self.tk_text_lc4fjiun = self.__tk_text_lc4fjiun()

    def __win(self):
        self.title("Tkinter布局助手")
        # 设置窗口大小、居中
        width = 550
        height = 280
        screenwidth = self.winfo_screenwidth()
        screenheight = self.winfo_screenheight()
        geometry = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
        self.geometry(geometry)
        self.resizable(width=False, height=False)

    def __tk_text_lc4fjiun(self):
        text = Text(self)
        text.place(x=0, y=0, width=550, height=280)

        vbar = Scrollbar(self)
        text.configure(yscrollcommand=vbar.set)
        vbar.config(command=text.yview)
        vbar.place(x=535, y=0, width=15, height=280)
        scrollbar_autohide(vbar, text)
        return text


class Win(WinGUI):
    def __init__(self):
        super().__init__()
        self.__event_bind()

    def __event_bind(self):
        pass


if __name__ == "__main__":
    win = Win()
    win.mainloop()
站长微信
请备注来意
二维码