Home > Software design >  How can I have a line gap between the question and the answer (Tkinter-python)
How can I have a line gap between the question and the answer (Tkinter-python)

Time:03-05

Basically, I want a gap of a line between the question and the answer. Also, how could I change the colour text on the answer part (to a red one) Example below.

Question 1

Answer 1

from tkinter import *

root = Tk()
root.title("Flashcard Revision")
root.geometry("700x500")
root.config(bg = "#3062C7")
i = 0
k = -1

def question():
    clear()
    global my_text, f, q_lines, i, k
    f = open("Unit1 questions.txt")
    q_lines = f.readlines()
    my_text.insert(1.0, q_lines[i])
    k = k   1
    i = i   1

def clear():
    my_text.delete(1.0, END)

def answer():
    global my_text, f, a_lines, k
    g = open("Unit1 answers.txt")
    a_lines = g.readlines()
    my_text.insert(2.0, a_lines[k])
    

q_button = Button(root, text="Question", bg="white", activebackground="red", command=question).place(x=285, y=280)

a_button = Button(root, text = "Answer", bg="white", activebackground="red", command=answer).place(x=355, y=280)

my_text = Text(root, width=40, height=10, font=("Helvetica", 16))
my_text.pack(pady=20)

root.mainloop()

CodePudding user response:

You can concatenate two newline characters('\n') at the end of each question string to render the answer after leaving a line in the text widget.

NOTE THIS LINE FROM THE OUTPUT

CODE USED FOR TESTING OUTPUT -:

from tkinter import *

root = Tk()
root.title("Flashcard Revision")
root.geometry("700x500")
root.config(bg = "#3062C7")
i = 0
k = -1

def question():
    clear()
    global my_text, f, q_lines, i, k
    q_lines = ['question1', 'question2', 'question3']
    my_text.insert('1.0', q_lines[i]   '\n\n')
    k = k   1
    i = i   1

def clear():
    my_text.delete('1.0', END)

def answer():
    global my_text, f, a_lines, k
    a_lines = ['answer1', 'answer2', 'answer3']
    my_text.insert('3.0', a_lines[k])
    

q_button = Button(root, text="Question", bg="white", activebackground="red", command=question).place(x=285, y=280)

a_button = Button(root, text = "Answer", bg="white", activebackground="red", command=answer).place(x=355, y=280)

my_text = Text(root, width=40, height=10, font=("Helvetica", 16))
my_text.pack(pady=20)

root.mainloop()

NOTE:

  • For more information about text widget indices refer to this.
  • For a proper guide on how to handle file objects refer to this.
  • Related