Align text with checkbox in tkinter

110 Views Asked by At

I'm trying to align the text with the checkboxes.

test image

Reading from a list in a text file but only the last checkbox align with the text.

import tkinter as tk

root = tk.Tk()
root.geometry("200x300") 
root.title("Test")

with open("test.txt", "r") as file:
    lines = file.readlines()

checkboxes = []
for line in lines:
    checkboxes.append(tk.IntVar())

for i, line in enumerate(lines):
    c = tk.Checkbutton(root, text=line, variable=checkboxes[i])
    c.pack()

root.mainloop()

test.txt:

Yellow
Blue
Red
White
Black
Orange

Guessing it has something to do with line breaks in the text file. What can I do to fix it?

1

There are 1 best solutions below

0
acw1668 On BEST ANSWER

There are trailing newline ("\n") characters at the end of the items except the last one.

You can use file.read().splitlines() instead to get rid of those newline characters:

with open("test.txt", "r") as file:
    #lines = file.readlines()
    lines = file.read().splitlines()