Python Tkinter:从CSV导入数据到OptionMenu显示异常求助
It looks like the problem stems from two key issues: how you're reading the CSV data into a list, and how you're passing that list to the OptionMenu constructor. Let's break down the fixes step by step.
1. Fix CSV Reading to Get a Flat List of Strings
Right now, when you use csv.reader, each row is returned as a single-element list (since you wrote each club name as a single column). Using dummy_club.extend(reader) adds each of these lists to your dummy_club, resulting in a nested list like [['Club1'], ['Club2'], ...]. Instead, we need to extract the string from each row to create a flat list.
Option A: Fix with csv.reader
import csv with open('clubs.csv', newline='') as club: reader = csv.reader(club) dummy_club = [] for row in reader: if row: # Skip empty rows dummy_club.append(row[0]) # Extract the first (only) element from each row
Option B: Simplify by Reading Plain Lines
Since you removed commas from club names, you can skip the CSV reader entirely and just read each line directly:
with open('clubs.csv', newline='') as club: dummy_club = [line.strip() for line in club if line.strip()]
2. Correctly Populate the OptionMenu
The OptionMenu constructor expects the variable followed by the options as positional arguments. You were passing the list as a value keyword argument, which is incorrect. Instead, unpack the list using * to pass each element as a separate option.
from tkinter import Tk, StringVar, OptionMenu app = Tk() sv_club = StringVar() # Set a default value if the list isn't empty if dummy_club: sv_club.set(dummy_club[0]) # Create OptionMenu with unpacked list of options d_club = OptionMenu(app, sv_club, *dummy_club) d_club.pack() app.mainloop()
Alternative: Add Options via the Menu (Consistent with Scrape Code)
If you prefer to use the same approach as your scrape function (adding commands to the menu), you can initialize the OptionMenu with a placeholder value, then loop through your dummy_club list to add each option:
app = Tk() sv_club = StringVar() # Initialize OptionMenu with a default placeholder d_club = OptionMenu(app, sv_club, "Select a Club") d_club.pack() # Get the menu widget from the OptionMenu m_club = d_club.children['menu'] # Clear any existing default options (optional) m_club.delete(0, 'end') # Add each club from the CSV list for val in dummy_club: m_club.add_command(label=val, command=lambda v=sv_club, l=val: v.set(l)) # Set default value if needed if dummy_club: sv_club.set(dummy_club[0]) app.mainloop()
Why This Works
- Fixing the CSV reading ensures you have a flat list of strings instead of nested lists, which Tkinter can interpret as individual menu options.
- Unpacking the list with
*in the OptionMenu constructor tells Tkinter to treat each string as a separate entry. - Using the menu's
add_commandmethod matches your existing scrape workflow, giving you consistent behavior across both loading scenarios.
内容的提问来源于stack exchange,提问作者exec85

