Skip to content Skip to sidebar Skip to footer

How Do I Fill The Rest Of My Screen Design With Blank Frames In Tkinter Using For Loop?

I am trying to make a shopping-inspired vending machine UI. The goal is to fill up my frame with frames using for loop and 2D list, then pack on buttons and labels onto it. Codes a

Solution 1:

You can actually use 1-D list instead of 2-D list. Below is an example based on your code:

from tkinter import *
import random

root = Tk()

store_canvas = Frame(root)
store_canvas.pack()

# create the 25 frames
ROWS = COLS = 5
MAX_ITEMS = ROWS * COLS
frames = []
for i in range(MAX_ITEMS):
    frames.append(Frame(store_canvas, width=1520/COLS, height=1030/ROWS, bd=2, relief=SOLID))
    frames[-1].grid(row=i//COLS, column=i%COLS)
    frames[-1].pack_propagate(False)

# function to simulate retrieving data from database table
def retrieve_tiem():
    return [f"Item #{i+1}" for i in range(random.randint(1,MAX_ITEMS))]

# function to show the retrieved items
def update_list():
    Item_list = retrieve_tiem()
    label_font = ("Arial", 20)
    for i, frame in enumerate(frames):
        for w in frame.winfo_children():
            w.destroy()
        if i < len(Item_list):
            item = Item_list[i]
            Button(frame).pack(fill="both", expand=1)
            Label(frame, text=item, font=label_font, bg="darkgreen", fg="yellow").pack(fill="x")

update_list()
root.bind("<F5>", lambda e: update_list())
root.mainloop()

Solution 2:

The problem is with your try statement. Here's an example:

a = 5
try:
    a += 7
    int("str") #This is just to raise an exception
except:
    pass

After running this code, the value of a will be 12, even though an error occured. This is the same thing that is happening in your code. The line that creates the button is run successfully, but the creating the label raises an exception. This is why you get buttons in the remaining space. This can be resolved using else. If we try this instead:

a = 5
try:
    int("str") #This is just to raise an exception
except:
    pass
else:
    a += 7

The a += 7 line will only be run if there is not exception in the try statement, so the value will remain 5. For your code, this will be

try:
    Item_list[num] #This is what causes the error
except:
    pass
else:
    Button(frame, anchor='nw', height = 9, width = 35, font = 20).pack()
    Label(frame, text=str(Item_list[num]), anchor='nw', font = 20, width = 35, bg = 'darkgreen', fg = 'yellow' ).pack()
    num += 1

Alternatively, you could have an if statement to check if num is larger than the length of the data returned, but there's not enough information in the question for me to be sure that will work.


Post a Comment for "How Do I Fill The Rest Of My Screen Design With Blank Frames In Tkinter Using For Loop?"