使用Tkinter创建多重选择

2021年5月11日14:33:22 发表评论 846 次浏览

先决条件: Python Tkinter – ListBox小部件, Python-tkinter中的可滚动列表框

Tkinter是python中的GUI库, 易于阅读和理解。在Tkinter中, 可以使用"列表框"窗口小部件完成多个选择。通常, 列表框以列表形式显示不同的项目。列表框小部件提供了列表中一项或多项的选择。列表框小部件中有许多可用选项, 使用户可以选择多个选项。通过将选择模式选项分配为多个, 用户可以选择多个选项。如果选择模式选项为单个, 则用户只能选择一个选项。

列表框窗口小部件的selectmode选项可以是单个, 浏览, 多个或扩展的。

  • 单–选择一行文本。
  • 浏览–这是默认选项, 用户可以选择一行文本。
  • 多–选择多行文本, 而不从选项的第一行拖到最后一行。
  • 扩展的–用户可以选择并拖动相邻的多行文本。

句法 :

list_box = Listbox(root, options, ....)

示例1:在列表框中显示有限项的Python程序。

# Python program demonstrating
# Multiple selection in Listbox widget
  
  
from tkinter import * 
  
window = Tk()
window.geometry( '100x150' )
  
# Choosing selectmode as multiple 
# for selecting multiple options
list = Listbox(window, selectmode = "multiple" )
  
# Widget expands horizontally and
# vertically by assigning both to 
# fill option
list .pack(expand = YES, fill = "both" )
  
# Taking a list 'x' with the items 
# as languages
x = [ "C" , "C++" , "Java" , "Python" , "R" , "Go" , "Ruby" , "JavaScript" , "Swift" ]
  
for each_item in range ( len (x)):
      
     list .insert(END, x[each_item])
      
     # coloring alternative lines of listbox
     list .itemconfig(each_item, bg = "yellow" if each_item % 2 = = 0 else "cyan" )
      
window.mainloop()

输出:

用户可以从上面的多个选择列表框中选择多个选项。由于列表框中的项目数量有限, 无法容纳规定的大小, 因此用户可以查看所有项目。但是, 如果有更多项目要显示给用户, 则所有这些项目在列表框中不会一次可见。因此, 如果列表中有更多项目要显示, 则必须将滚动条附加到列表框。这可以通过yscroll命令列表框中的选项(垂直滚动)。

示例2:Python程序显示带有附加滚动条的列表框。

# Python program demonstrating Multiple selection
# in Listbox widget with a scrollbar
  
  
from tkinter import *
  
window = Tk()
window.title( 'Multiple selection' )
  
# for scrolling vertically
yscrollbar = Scrollbar(window)
yscrollbar.pack(side = RIGHT, fill = Y)
  
label = Label(window, text = "Select the languages below :  " , font = ( "Times New Roman" , 10 ), padx = 10 , pady = 10 )
label.pack()
list = Listbox(window, selectmode = "multiple" , yscrollcommand = yscrollbar. set )
  
# Widget expands horizontally and 
# vertically by assigning both to
# fill option
list .pack(padx = 10 , pady = 10 , expand = YES, fill = "both" )
  
x = [ "C" , "C++" , "C#" , "Java" , "Python" , "R" , "Go" , "Ruby" , "JavaScript" , "Swift" , "SQL" , "Perl" , "XML" ]
  
for each_item in range ( len (x)):
      
     list .insert(END, x[each_item])
     list .itemconfig(each_item, bg = "lime" )
  
# Attach listbox to vertical scrollbar
yscrollbar.config(command = list .yview)
window.mainloop()

输出:

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: