Search code examples
python-3.xloopstkinteroperating-systemtkinter-layout

i want answer in horizontal loop with desire number of space in tkinter


#i dont know whts worng i want result in horizontal format with desire space between them

from tkinter import *
import os

window = Tk()
window.title("Window") #window dimensions
window.configure(bg = "black")
HEIGHT = window.winfo_screenheight()  #height and width
WIDTH = window.winfo_screenwidth()
RESOL = str(WIDTH) + "x" + str(HEIGHT+7) + "+" + str(-7) + "+" + str(0)
window.geometry(RESOL)

l = os.listdir("D:/anime")
l1 = l[0:5]         #five number of files
x = 0
y = 0
count = 0
for item in l1:     #its working well but it give result in vertical loop 
    Label(window, text = item, bg = "green").place(x = x, y = y)
    y += 30         #i want result in horizontal loop with desire number of space between
window.mainloop()

Solution

  • If you want a horizontal row of labels, it's much easier to use pack than place. place requires a lot more work and isn't responsive unless you do even more work to make it responsive.

    Instead, create a frame for the labels and use pack:

    label_frame = Frame(window)
    label_frame.pack(side="top", fill="x")
    
    for item in l1:
        label = Label(label_frame, text=item, bg="green")
        label.pack(side="left")
    

    If you want to control the space between widgets, add some padding by either specifying a single value for padx which adds space to both sides, or just add space to the right of every widget using a 2-tuple. In the following example it adds 10 pixels to the right of every widget and 0 pixels to the left:

    label.pack(side="left", padx=(0, 10))