📜  Python-tkinter 中的可滚动列表框

📅  最后修改于: 2022-05-13 01:55:05.945000             🧑  作者: Mango

Python-tkinter 中的可滚动列表框

Tkinter 是Python的标准 GUI 库。 Python中的 Tkinter 带有很多很好的小部件。 Widgets 是标准的 GUI 元素,Listbox、Scrollbar 也会在这个 Widgets 之下。

注意:更多信息请参考Python GUI – tkinter

列表框

ListBox 小部件用于显示不同类型的项目。这些项目必须是相同类型的字体并且具有相同的字体颜色。这些项目也必须是文本类型。用户可以根据需要从给定的列表中选择一项或多项。

句法:

listbox = Listbox(root, bg, fg, bd, height, width, font, ..)

将滚动条添加到 ListBox-Python

滚动条

滚动条小部件用于向下滚动内容。我们还可以为 Entry 小部件创建水平滚动条。

句法:
下面给出了使用 Scrollbar 小部件的语法。

w = Scrollbar(master, options) 

参数:

  • master :此参数用于表示父窗口。
  • options :有许多可用的选项,它们可以用作以逗号分隔的键值对。

将滚动条添加到 ListBox-Python

将滚动条添加到 ListBox

为此,我们需要将滚动条附加到 Listbox,并使用函数listbox.config()并将其命令参数设置为滚动条的 set 方法,然后将滚动条的命令参数设置为指向一个方法,该方法将在滚动条位置改变

from tkinter import *
  
  
# Creating the root window
root = Tk()
  
# Creating a Listbox and
# attaching it to root window
listbox = Listbox(root)
  
# Adding Listbox to the left
# side of root window
listbox.pack(side = LEFT, fill = BOTH)
  
# Creating a Scrollbar and 
# attaching it to root window
scrollbar = Scrollbar(root)
  
# Adding Scrollbar to the right
# side of root window
scrollbar.pack(side = RIGHT, fill = BOTH)
  
# Insert elements into the listbox
for values in range(100):
    listbox.insert(END, values)
      
# Attaching Listbox to Scrollbar
# Since we need to have a vertical 
# scroll we use yscrollcommand
listbox.config(yscrollcommand = scrollbar.set)
  
# setting scrollbar command parameter 
# to listbox.yview method its yview because
# we need to have a vertical view
scrollbar.config(command = listbox.yview)
  
root.mainloop()

输出
将滚动条添加到 ListBox-Python