高中计算机项目:Tkinter按钮复用与Notebook当前帧获取问题
Hey Danny, let's work through your two Tkinter challenges for your restaurant menu app—they're totally solvable with a few smart tweaks!
Right now, your add() and subtra() functions have no way of knowing which button was clicked. We can fix this by passing the category index (i) and dish index (j) to each function using lambda when creating the buttons. Also, I spotted a bug in how you initialized your Count list—all rows are currently referencing the same list, so updating one would accidentally update every dish's count. Let's fix that first.
Step 1: Fix the Count list initialization
Replace your current Count setup with this to ensure each dish has its own independent count:
# Number of servings ordered Count = [[0]*4 for _ in range(len(catename))] # Each row is a unique list
Step 2: Update button commands to pass indices
When creating your add and minus buttons, use lambda to pass the i and j values. This tells the functions exactly which dish to modify:
# Add Button Buttonsadd=[] for i in range(0, len(catename)): single=[] for j in range(0, 4): # Use lambda to bind i and j to the add function single.append(Button(cate[i], text="+", command=lambda i=i, j=j: add(i,j))) Buttonsadd.append(single) # Minus Button Buttonsminus=[] for i in range(0, len(catename)): single=[] for j in range(0, 4): # Same logic for the subtract function single.append(Button(cate[i], text="-", command=lambda i=i, j=j: subtra(i,j))) Buttonsminus.append(single)
Step 3: Implement the add and subtra functions
Now update your functions to use the indices to adjust the count and refresh the corresponding label:
def add(i, j): Count[i][j] += 1 countlables[i][j].config(text=str(Count[i][j])) def subtra(i, j): if Count[i][j] > 0: # Prevent negative counts Count[i][j] -= 1 countlables[i][j].config(text=str(Count[i][j]))
With these changes, every + and - button will trigger the right function with the correct dish indices, and you only need two functions total—no more 100 separate functions!
Tkinter's ttk.Notebook has two straightforward ways to get the currently active frame:
Method 1: Get the frame directly using nametowidget()
The select() method returns the internal name of the selected tab. You can convert this name to the actual Frame object with nametowidget():
# Fetch the currently selected frame current_tab_id = menu.select() current_frame = menu.nametowidget(current_tab_id)
Method 2: Use the tab index with your existing cate list
Alternatively, get the index of the selected tab and pull the frame from your pre-made cate list:
current_tab_index = menu.index(menu.select()) current_frame = cate[current_tab_index]
Both methods work perfectly—pick whichever fits your workflow better. For example, if you need to modify widgets on the active tab, either approach lets you reference the frame directly.
内容的提问来源于stack exchange,提问作者Danny Yang

