tkinter 菜单显示的输入问题

问题描述 投票:0回答:1

我拥有显示菜单项及其详细信息的菜单的大部分代码,这在大多数情况下都有效。我遇到的主要问题是当我按下按钮时,例如“byte Burger”,它显示错误的菜单项/详细信息,此外,当我打开菜单时,它最初应该显示“byte Burger”的详细信息,但它显示的是错误的。

import tkinter as tk

class BurgerMenuApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Codetown Burger Co Menu")
        self.current_index = 0
        self.label = tk.Label(self.root, text="")
        self.label.pack(pady=10)

        # define menuu items
        self.menu_items = [
            {"name": "Byte Burger", "bun": "Milk bun", "sauce": "Tomato sauce", "patties": 1, "cheese": 0, "tomato": False, "lettuce": True, "onion": False},
            {"name": "Ctrl-Alt-Delicious", "bun": "Milk bun", "sauce": "Barbecue sauce", "patties": 2, "cheese": 2, "tomato": True, "lettuce": True, "onion": True},
            {"name": "Data Crunch", "bun": "Gluten free bun", "sauce": "Tomato sauce", "patties": 0, "cheese": 0, "tomato": True, "lettuce": True, "onion": True},
            {"name": "Code Cruncher", "bun": "Milk bun", "sauce": "Tomato sauce", "patties": 3, "cheese": 3, "tomato": True, "lettuce": True, "onion": True},
        ]

        self.display_menu_item()

        self.create_buttons()

        self.auto_cycle()

    def display_menu_item(self):
        item = self.menu_items[self.current_index]
        details = f"Name: {item['name']}\nBun: {item['bun']}\nSauce: {item['sauce']}\nPatties: {item['patties']}\nCheese: {item['cheese']}\nTomato: {'Yes' if item['tomato'] else 'No'}\nLettuce: {'Yes' if item['lettuce'] else 'No'}\nOnion: {'Yes' if item['onion'] else 'No'}"
        self.label.config(text=details)

    def create_buttons(self):
        for index, item in enumerate(self.menu_items):
            button = tk.Button(self.root, text=item["name"], command=lambda i=index: self.select_menu_item(i))
            button.pack(pady=5)

    def select_menu_item(self, index):
        self.current_index = index
        self.display_menu_item()
        if getattr(self, 'cycle_timer', None):
            self.root.after_cancel(self.cycle_timer)
        self.auto_cycle()

    def auto_cycle(self):
        if getattr(self, 'auto_cycle_enabled', True):
           self.current_index = (self.current_index + 1) % len(self.menu_items)
           self.display_menu_item()
           # Set a timer for the next cycle
           self.cycle_timer = self.root.after(5000, self.auto_cycle)

root = tk.Tk()
app = BurgerMenuApp(root)
root.mainloop()

python tkinter
1个回答
0
投票

我遇到的主要问题是当我按下按钮时,例如'字节汉堡', 它显示错误的菜单项/详细信息,

问题可以解决。

26号线:

更改此:

item = self.menu_items[self.current_index]

至:

item = self.menu_items[self.current_index - 1] #change index to -1

33号线:

更改此:

command=lambda i=index: self.select_menu_item(i))

至:

command=lambda i=index: self.select_menu_item(i+1)) #change index to +1

36号线:

self.current_index = index

至:

self.current_index = index-1 #change index to -1

你准备好了。

截图:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.