当前位置:   article > 正文

Python tkinter自定义多选下拉列表框(带滚动条、全选)_tkinter 下拉框选择

tkinter 下拉框选择

包括3个文件:
1、demo.py文件
2、ComBoPicker.py文件
3、ComBoPicker1.py文件

问题方法
怎么动态赋值COMBOPICKER.values = [1,2,3,4]
获取选中值1.COMBOPICKER.current_value
2.COMBOPICKER.get()
3.COMBOPICKER.entry_var.get()

效果如下图:

demo.py文件

  1. from tkinter import *
  2. from ComBoPicker import Combopicker# 导入自定义下拉多选框
  3. from ComBoPicker1 import Combopicker as Combopicker1# 导入自定义下拉多选框
  4. if __name__ == "__main__":
  5. root = Tk()
  6. root.geometry("300x300")
  7. F =Frame(root)
  8. F.pack(expand=False, fill="both",padx=10,pady=10)
  9. Label(F,text='全选、可滚动:').pack(side='left')
  10. COMBOPICKER = Combopicker(F, values = ['全选','项目1','项目2','项目3','项目4','项目5','项目11','项目22','项目33','项目44','项目55'])
  11. COMBOPICKER.pack(anchor="w")
  12. F2 =Frame(root)
  13. F2.pack(expand=False, fill="both",padx=10,pady=10)
  14. Label(F2,text='普通:').pack(side='left')
  15. COMBOPICKER1 = Combopicker1(F2, values = [f'项目{i}' for i in range(5)])
  16. COMBOPICKER1.pack(anchor="w")
  17. root.mainloop()

ComBoPicker.py文件

  1. '''
  2. 自定义多选下拉列表
  3. '''
  4. import tkinter.font as tkFont
  5. import tkinter.ttk as ttk
  6. from tkinter import *
  7. class Picker(ttk.Frame):
  8. def __init__(self, master=None,activebackground='#b1dcfb',values=[],entry_wid=None,activeforeground='black', selectbackground='#003eff', selectforeground='white', command=None, borderwidth=1, relief="solid"):
  9. self._selected_item = None
  10. self._values = values
  11. self._entry_wid = entry_wid
  12. self._sel_bg = selectbackground
  13. self._sel_fg = selectforeground
  14. self._act_bg = activebackground
  15. self._act_fg = activeforeground
  16. self._command = command
  17. ttk.Frame.__init__(self, master, borderwidth=borderwidth, relief=relief)
  18. self.bind("<FocusIn>", lambda event:self.event_generate('<<PickerFocusIn>>'))
  19. self.bind("<FocusOut>", lambda event:self.event_generate('<<PickerFocusOut>>'))
  20. self._font = tkFont.Font()
  21. self.dict_checkbutton = {}
  22. self.dict_checkbutton_var = {}
  23. self.dict_intvar_item = {}
  24. for index,item in enumerate(self._values):
  25. self.dict_intvar_item[item] = IntVar()
  26. self.dict_checkbutton[item] = ttk.Checkbutton(self, text = item, variable=self.dict_intvar_item[item],command=lambda ITEM = item:self._command(ITEM))
  27. self.dict_checkbutton[item].grid(row=index, column=0, sticky=NSEW)
  28. self.dict_intvar_item[item].set(0)
  29. class Combopicker(ttk.Entry, Picker):
  30. def __init__(self, master, values= [] ,entryvar=None, entrywidth=None, entrystyle=None, onselect=None,activebackground='#b1dcfb', activeforeground='black', selectbackground='#003eff', selectforeground='white', borderwidth=1, relief="solid"):
  31. self.values=values
  32. if entryvar is not None:
  33. self.entry_var = entryvar
  34. else:
  35. self.entry_var = StringVar()
  36. entry_config = {}
  37. if entrywidth is not None:
  38. entry_config["width"] = entrywidth
  39. if entrystyle is not None:
  40. entry_config["style"] = entrystyle
  41. ttk.Entry.__init__(self, master, textvariable=self.entry_var, **entry_config, state = "readonly")
  42. self._is_menuoptions_visible = False
  43. self.picker_frame = Picker(self.winfo_toplevel(), values=values,entry_wid = self.entry_var,activebackground=activebackground, activeforeground=activeforeground, selectbackground=selectbackground, selectforeground=selectforeground, command=self._on_selected_check)
  44. self.bind_all("<1>", self._on_click, "+")
  45. self.bind("<Escape>", lambda event: self.hide_picker())
  46. @property
  47. def current_value(self):
  48. try:
  49. value = self.entry_var.get()
  50. return value
  51. except ValueError:
  52. return None
  53. @current_value.setter
  54. def current_value(self, INDEX):
  55. self.entry_var.set(self.values.index(INDEX))
  56. def _on_selected_check(self, SELECTED):
  57. value = []
  58. if self.entry_var.get() != "" and self.entry_var.get() != None:
  59. temp_value = self.entry_var.get()
  60. value = temp_value.split(",")
  61. if str(SELECTED) in value:
  62. value.remove(str(SELECTED))
  63. else:
  64. value.append(str(SELECTED))
  65. value.sort()
  66. temp_value = ""
  67. for index,item in enumerate(value):
  68. if item!= "":
  69. if index != 0:
  70. temp_value += ","
  71. temp_value += str(item)
  72. self.entry_var.set(temp_value)
  73. def _on_click(self, event):
  74. str_widget = str(event.widget)
  75. if str_widget == str(self):
  76. if not self._is_menuoptions_visible:
  77. self.show_picker()
  78. else:
  79. if not str_widget.startswith(str(self.picker_frame)) and self._is_menuoptions_visible:
  80. self.hide_picker()
  81. def show_picker(self):
  82. if not self._is_menuoptions_visible:
  83. self.picker_frame.place(in_=self, relx=0, rely=1, relwidth=1 )
  84. self.picker_frame.lift()
  85. self._is_menuoptions_visible = True
  86. def hide_picker(self):
  87. if self._is_menuoptions_visible:
  88. self.picker_frame.place_forget()
  89. self._is_menuoptions_visible = False
'
运行

ComBoPicker1.py文件

  1. '''
  2. 自定义多选下拉列表
  3. '''
  4. import tkinter.font as tkFont
  5. import tkinter.ttk as ttk
  6. from tkinter import *
  7. class Picker(ttk.Frame):
  8. def __init__(self, master=None,activebackground='#b1dcfb',values=[],entry_wid=None,activeforeground='black', selectbackground='#003eff', selectforeground='white', command=None, borderwidth=1, relief="solid"):
  9. self._selected_item = None
  10. self._values = values
  11. self._entry_wid = entry_wid
  12. self._sel_bg = selectbackground
  13. self._sel_fg = selectforeground
  14. self._act_bg = activebackground
  15. self._act_fg = activeforeground
  16. self._command = command
  17. ttk.Frame.__init__(self, master, borderwidth=borderwidth, relief=relief)
  18. self.bind("<FocusIn>", lambda event:self.event_generate('<<PickerFocusIn>>'))
  19. self.bind("<FocusOut>", lambda event:self.event_generate('<<PickerFocusOut>>'))
  20. self._font = tkFont.Font()
  21. self.dict_checkbutton = {}
  22. self.dict_checkbutton_var = {}
  23. self.dict_intvar_item = {}
  24. for index,item in enumerate(self._values):
  25. self.dict_intvar_item[item] = IntVar()
  26. self.dict_checkbutton[item] = ttk.Checkbutton(self, text = item, variable=self.dict_intvar_item[item],command=lambda ITEM = item:self._command(ITEM))
  27. self.dict_checkbutton[item].grid(row=index, column=0, sticky=NSEW)
  28. self.dict_intvar_item[item].set(0)
  29. class Combopicker(ttk.Entry, Picker):
  30. def __init__(self, master, values= [] ,entryvar=None, entrywidth=None, entrystyle=None, onselect=None,activebackground='#b1dcfb', activeforeground='black', selectbackground='#003eff', selectforeground='white', borderwidth=1, relief="solid"):
  31. self.values=values
  32. if entryvar is not None:
  33. self.entry_var = entryvar
  34. else:
  35. self.entry_var = StringVar()
  36. entry_config = {}
  37. if entrywidth is not None:
  38. entry_config["width"] = entrywidth
  39. if entrystyle is not None:
  40. entry_config["style"] = entrystyle
  41. ttk.Entry.__init__(self, master, textvariable=self.entry_var, **entry_config, state = "readonly")
  42. self._is_menuoptions_visible = False
  43. self.picker_frame = Picker(self.winfo_toplevel(), values=values,entry_wid = self.entry_var,activebackground=activebackground, activeforeground=activeforeground, selectbackground=selectbackground, selectforeground=selectforeground, command=self._on_selected_check)
  44. self.bind_all("<1>", self._on_click, "+")
  45. self.bind("<Escape>", lambda event: self.hide_picker())
  46. @property
  47. def current_value(self):
  48. try:
  49. value = self.entry_var.get()
  50. return value
  51. except ValueError:
  52. return None
  53. @current_value.setter
  54. def current_value(self, INDEX):
  55. self.entry_var.set(self.values.index(INDEX))
  56. def _on_selected_check(self, SELECTED):
  57. value = []
  58. if self.entry_var.get() != "" and self.entry_var.get() != None:
  59. temp_value = self.entry_var.get()
  60. value = temp_value.split(",")
  61. if str(SELECTED) in value:
  62. value.remove(str(SELECTED))
  63. else:
  64. value.append(str(SELECTED))
  65. value.sort()
  66. temp_value = ""
  67. for index,item in enumerate(value):
  68. if item!= "":
  69. if index != 0:
  70. temp_value += ","
  71. temp_value += str(item)
  72. self.entry_var.set(temp_value)
  73. def _on_click(self, event):
  74. str_widget = str(event.widget)
  75. if str_widget == str(self):
  76. if not self._is_menuoptions_visible:
  77. self.show_picker()
  78. else:
  79. if not str_widget.startswith(str(self.picker_frame)) and self._is_menuoptions_visible:
  80. self.hide_picker()
  81. def show_picker(self):
  82. if not self._is_menuoptions_visible:
  83. self.picker_frame.place(in_=self, relx=0, rely=1, relwidth=1 )
  84. self.picker_frame.lift()
  85. self._is_menuoptions_visible = True
  86. def hide_picker(self):
  87. if self._is_menuoptions_visible:
  88. self.picker_frame.place_forget()
  89. self._is_menuoptions_visible = False
'
运行

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/813336
推荐阅读
相关标签
  

闽ICP备14008679号