如果正确的tkinter,使按钮转到下一行

时间:2016-12-27 04:43:52

标签: python tkinter

我目前正在学校学习python和冬天休息,所以我真的想学习python的GUI,所以我开始学习tkinter。目前我正在尝试这样做,所以每次用户得到正确的答案它将移动到文件中的下一行,但我不知道如何做到这一点,我已经整天尝试这样做只是为了确保我没有遗漏任何东西但无法找到我想要的东西,如果有人能帮助我,我会很高兴。

def correctquestion(e):
correct.configure(text="Correct")


def incorrectquestion(e):
    correct.configure(text="Incorrect")


def lines(e):
    file_name = open("state_capitals.txt", "r")
    line = file_name.readline().strip().split(",")

    return line

def nextquestion(e):
    line = lines(e)
    data = answerBox.get()

    if line[1] == data:
        correctquestion(e)
        questionBox.configure(text=line[0])
    else:
        incorrectquestion(e)
        questionBox.configure(text=line[0])

root = Tk()
frame = Frame(root)
Grid.rowconfigure(root, 0, weight=0)
Grid.columnconfigure(root, 0, weight=1)
frame.grid(row=0, column=0)
root.geometry('{}x{}'.format(500, 500))
root.resizable(width=False, height=False)

line = lines(root)


AnswerButton = Button(root, text="Submit")
AnswerButton.grid(row=3, sticky=W, padx=(80, 10))
AnswerButton.bind("<Button-1>", nextquestion)

questionBox = Label(root, text=line[0], bg="red", fg="white")
questionBox.config(font=("Courier", 30))
questionBox.grid(row=0, sticky=W + E, ipady=30)

root.mainloop()

1 个答案:

答案 0 :(得分:2)

更好地阅读所有文件并将所有行保留在内存中 - 这将更容易。

示例代码 - 未经测试 - 我没有问题的文件:)

import tkinter as tk

# --- functions --- (lower_case names)

def read_file():
    file_ = open("state_capitals.txt")

    # create list of lines
    lines = file_.read().split('\n')

    # split every line in columns
    lines = [l.split(',') for l in lines]

    return lines

def next_question():
    global current_question # inform function to use global variable instead local because we will assign new value

    data = answer_Box.get()

    if all_lines[current_question][1] == data:
        correct.configure(text="Correct")
        current_question += 1
        if current_question < len(all_lines):
            question_box.configure(text=all_lines[current_question][0])
        else:
            question_box.configure(text="THE END")
    else:
        correct.configure(text="Incorrect")

# --- main --- (lower_case names)

all_lines = read_file()
current_question = 0 # create global variable

root = tk.Tk()
root.geometry('500x500')
root.resizable(width=False, height=False)

root.rowconfigure(0, weight=0)
root.columnconfigure(0, weight=1)

answer_button = tk.Button(root, text="Submit", command=next_question)
answer_button.grid(row=3, sticky='w', padx=(80, 10))

question_box = tk.Label(root, text=all_lines[current_question][0],
                        bg="red", fg="white", font=("Courier", 30))
question_box.grid(row=0, sticky='we', ipady=30)

correct = tk.Label(root)
correct.grid(row=1, sticky='we', ipady=30)

root.mainloop()

BTW:PEP 8 -- Style Guide for Python Code