python中的提示卡程序

时间:2017-02-05 11:06:20

标签: python list tkinter

之前我曾向此提出过类似的问题,但我似乎永远无法找到一个正常运行的解决方案(很可能是因为我缺乏编程知识)

我正在尝试创建一个“提示卡”系统。将卡添加到程序中,将它们存储在某些卡座中,然后让这些卡片在被要求时输出卡片。我使用Tkinter作为我的GUI。到目前为止,这是我的代码;

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:
        question_list.append(question)
    if topic not in topic_list:
        topic_list.append(topic)
    x -=1

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

for topic, question in zip(topic_list, question_list):
    data[topic].append(question)

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

root.mainloop()

它向用户询问5个问题,然后将“主题”的按钮添加到根窗口。单击此主题按钮时,我希望它仅显示该主题中的问题。但是目前显示所有问题。我尝试过使用词典,但似乎没有用。任何帮助非常感谢。 (When I have clicked the maths button this is the Output of the program

编辑后

我认为字典的垮台是使用zip方法,因为不是每个项目都会在列表中配对,但我真的不确定。使用字典并单击数学按钮时的输出显示为here

1 个答案:

答案 0 :(得分:1)

我将topic-question直接添加到data,并仅保留topic_list来创建按钮。

我使用topic发送lambda函数以分配带参数的按钮函数。

因为lambda中的for-loop可能会有误,所以我使用arg=topic代替直接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)
        button.pack()

# --- 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:
        topic_list.append(topic)

    # add topic-question directly to data
    data[topic].append(question)

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))
    button.pack()

root.mainloop()