报错NameError: name 'ttk' is not defined,创建Combobox遇问题求助
NameError: name 'ttk' is not defined for your Combobox Hey there! Let's get that currency calculator back on track. The error you're seeing happens because ttk is a sub-module of tkinter (Python's built-in GUI library) and you haven't imported it yet. 2016 tutorials sometimes skip over this step assuming basic knowledge, but no worries—we'll fix it in two quick steps.
Step 1: Import the required modules
At the very top of your Python file, add these lines to import tkinter and its ttk sub-module:
import tkinter as tk from tkinter import ttk
import tkinter as tklets you use all core tkinter components with a short alias (tk.instead of typingtkinter.every time)from tkinter import ttkmakes thettkmodule directly available, so you can usettk.Comboboxwithout extra prefixes
Alternatively, you could import ttk like this if you prefer:
import tkinter.ttk as ttk
Either way will resolve the NameError.
Step 2: Make sure your other variables are properly set up
Your Combobox code references LeftMainFrame and value0—you'll need to define those too (the tutorial probably covered this earlier, but it's easy to miss!). Here's a complete working example that includes all necessary parts:
import tkinter as tk from tkinter import ttk # Create the main application window root = tk.Tk() root.title("Currency Calculator") # Create your LeftMainFrame (a container for your Combobox) LeftMainFrame = ttk.Frame(root, padding=15) LeftMainFrame.grid(row=0, column=0) # Define the StringVar for your Combobox's textvariable value0 = tk.StringVar() # Your Combobox code (now with ttk properly imported!) box = ttk.Combobox(LeftMainFrame, textvariable=value0, state='readonly', font=('arial', 20, 'bold'), width=20) box['values'] = (' ', 'USA', 'Kenya', 'Brazil', 'Canada', 'India', 'Philippines') # Fixed the spelling of Philippines! box.current(0) box.grid(row=4, column=2) # Start the GUI event loop (required to show the window) root.mainloop()
A quick note: I fixed the spelling of "Phillappines" to "Philippines" in the values list—small typo, but it's good to clean up!
Why this works
ttk provides modern-looking GUI widgets (like the Combobox) that are separate from the older, classic tkinter widgets. You have to explicitly import it because it's not included in the base tkinter import.
Give this code a run in Visual Studio, and your Combobox should show up without errors. If you hit any other snags (like issues with LeftMainFrame or layout), feel free to ask for more help!
内容的提问来源于stack exchange,提问作者svgeeer




