我正在嘗試創建一個簡單的隨機取餐器。我希望它允許用戶從多個成分復選框中進行選擇,然后獲取它制作的新串列并讓它索引其他餐點串列,然后使用 random.choice 選項讓它只建議具有所有成分的餐點成分(串列項)由用戶勾選。
所以這個想法是它將從選定的復選框中創建一個名為 cb_vars 的串列。這將是一個成分串列,然后我希望它掃描每個串列以查看是否有任何串列具有在 cb_vars 中表示的所有成分,然后它將獲取所有符合該標準的串列并列出這些食譜(串列名稱)并隨機選擇一個。
我嘗試了幾種不同的方法,但似乎無法弄清楚。我是新手,正在努力自學。
import random
from tkinter import *
root = Tk()
category_data = ['Ground Beef', 'Cheese', 'Buns', 'Bacon', 'Eggs', 'Mushrooms', 'Egg Noodles', 'Gravy']
meals = ['burgers', 'omelettes']
burgers = ['Ground Beef', 'Cheese', 'Buns']
omelettes = ['Eggs', 'Cheese', 'Bacon']
selected_meals = []
cb_vars = {} # dict to store the BooleanVar
for category in category_data:
var = BooleanVar()
l = Checkbutton(root, text=category, variable=var, onvalue=True, offvalue=False)
l.pack(anchor=W)
cb_vars[category] = var # store the BooleanVar
check = any(item in cb_vars for item in burgers or omelettes)
def select_meals():
check
if check is True:
print(random.choice(check))
else:
print("You need to go shopping.")
Button(root, text="Randomize Meal", command=select_meals).pack()
root.mainloop()
uj5u.com熱心網友回復:
您的編碼嘗試中存在多個問題,需要解決這些問題才能使代碼提供預期的結果。通過邊做邊學,您現在有機會了解以下代碼如何提供請求的結果。這將使您能夠擴展或修改代碼以更好地適應您的需求:
import random
from tkinter import Tk, Checkbutton, BooleanVar, Button, W
root = Tk()
category_data = ['Ground Beef', 'Cheese', 'Buns', 'Bacon', 'Eggs', 'Mushrooms', 'Egg Noodles', 'Gravy']
meals = ['burgers', 'omelettes']
burgers = ['Ground Beef', 'Cheese', 'Buns']
omelettes = ['Eggs', 'Cheese', 'Bacon']
cb_vars = [] # list to store the BooleanVar
indx = 0
for category in category_data:
cb_vars.append(BooleanVar())
l = Checkbutton(root, text=category, variable=cb_vars[indx], onvalue=True, offvalue=False)
indx = indx 1 # store the BooleanVar list index == index to category_data
l.pack(anchor=W)
def select_meals():
availableMeals = []
categoryChoice = []
for indx, cb_var in enumerate(cb_vars):
if cb_var.get() is True:
categoryChoice.append(category_data[indx])
print(categoryChoice)
for meal in meals:
mealFits = True
for choice in categoryChoice:
if choice in eval(meal): # eval() returns a list with ingredients
pass # meal OK
else:
mealFits = False
if mealFits:
availableMeals.append(meal)
if len(availableMeals) == 0:
print("You need to go shopping.")
else:
print('Available:', availableMeals)
print('Choice: ', random.choice(availableMeals))
Button(root, text="Randomize Meal", command=select_meals).pack()
root.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/491109.html
