Seb Seb - 4 years ago 162
Python Question

Cue Card program in python

I have asked a similar question to this before but I can never seem to get a solution that works properly (most likely down to my lack of programming knowledge)

I am trying to create a "cue card" system. Adding cards to a program, storing them in certain decks and then having these decks output their cards when asked to. I am using Tkinter as my GUI for this. So far this is my code;

from tkinter import *
root = Tk()

question_list = []
topic_list = []
data = defaultdict(list)

x = 5
while x > 0:
question = input("what is your question?")
topic = input("what is the topic of the question?")
if question not in question_list:
if topic not in topic_list:
x -=1

def display_deck():
top = Toplevel()
for i in data:
if i == topic:
button2 = Button(top, text=data[i], fg="black")

for topic, question in zip(topic_list, question_list):

for y in topic_list:
button = Button(root, text=y, fg="black", command=display_deck)


It asks the user 5 questions and then adds the button of the "topic" to the root window. When this topic button is clicked I want it to display just the questions in that topic. However currently it displays all the questions. I have tried using dictionaries but that didn't seem to work. Any help greatly appreciated.
(When I have clicked the maths button this is the Output of the program)

After Edit

I think the downfall of the dictionary is using the zip method as not every item will be paired up in the list but I am really not sure. The output when using a dictionary and clicking the maths button is seen here

Answer Source

I add topic-question directly to data and keep only topic_list to create buttons.

I send topic to function using lambda to assign to button function with argument.

Because lambda in for-loop can work strange so I use arg=topic instead of directly display_deck(topic)

import tkinter as tk
from collections import defaultdict

# --- functions ---

def display_deck(topic):
    top = tk.Toplevel()
    for question in data[topic]: 
        button = tk.Button(top, text=question)

# --- main ---

topic_list = []
data = defaultdict(list)

# ask for 5 question-topic
for _ in range(5):
    question = input("what is your question?")
    topic = input("what is the topic of the question?")

    # keep topic to create buttons
    if topic not in topic_list:

    # add topic-question directly to data

root = tk.Tk()

# create buttons 
for topic in topic_list:
    # assign function with argument
    button = tk.Button(root, text=topic, command=lambda arg=topic:display_deck(arg))

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download