Tkinter中选择Combobox选项时Listbox选中状态被重置的解决方法
解决Tkinter Listbox选中状态被Combobox重置的问题
问题根源在于Tkinter的Listbox默认开启了exportselection属性(值为True),当Listbox失去焦点(比如点击Combobox)时,系统会清除它的选中状态,保证同一时间只有一个控件的选中内容被系统共享。
只需要在创建Listbox时添加exportselection=False参数,就能阻止选中状态被自动清除:
self.box = tk.Listbox(frame, selectmode=tk.MULTIPLE, height=4, exportselection=False)
修改后的完整代码如下:
import tkinter as tk from tkinter import ttk class CheckboxDropdownApp: def __init__(self, master): self.master = master self.master.title('List box with Scrollbar and Dropdown') self.create_widgets() def create_widgets(self): # Create a frame to hold the Listbox, Scrollbar, and Combobox frame = tk.Frame(self.master) frame.pack() # Create a Listbox with a scrollbar,添加exportselection=False self.box = tk.Listbox(frame, selectmode=tk.MULTIPLE, height=4, exportselection=False) scrollbar = tk.Scrollbar(frame, orient=tk.VERTICAL, command=self.box.yview) self.box.config(yscrollcommand=scrollbar.set) values = ['Red', 'Green', 'Blue', 'Purple', 'Yellow', 'Orange', 'Black', 'White'] for val in values: # Add padding to each item padded_val = f" {val} " self.box.insert(tk.END, padded_val) self.box.pack(side=tk.LEFT, padx=10, pady=10) scrollbar.pack(side=tk.RIGHT, fill=tk.Y) # Create a Combobox self.dropdown_var = tk.StringVar() self.dropdown = ttk.Combobox(frame, values=values, textvariable=self.dropdown_var) self.dropdown.set(values[0]) self.dropdown.pack(pady=10) # Create buttons show_button = tk.Button(self.master, text='Show', width=25, command=self.clicked) show_button.pack() close_button = tk.Button(self.master, text='Close', width=25, command=self.master.destroy) close_button.pack() def clicked(self): selected = self.box.curselection() # returns a tuple dropdown_value = self.dropdown_var.get() if not selected and not dropdown_value: print("No item selected.") else: print("Selected items:") for idx in selected: print(self.box.get(idx).strip()) # Remove padding when printing print(f"Dropdown selected value: {dropdown_value}") def main(): root = tk.Tk() app = CheckboxDropdownApp(root) root.mainloop() if __name__ == "__main__": main()
exportselection=False会禁用控件选中内容的系统级共享,这样Listbox在失去焦点时就能保留自身的选中状态,不会被Combobox的操作重置。
内容的提问来源于stack exchange,提问作者Tester
相关产品推荐
相关产品推荐

