Making a window UI scroll down and deleting labels from frame

Viewed 35

I am making a random generator for my friends and I'm stuck trying to make a scroll down option. So if you generate more the window can show, a scroll down window should be possible. But I can't seem to get any to work. I've tried many online tutorials.

And my second issue with my code is that I can't clear the generated labels from the window. I got it working that it expands the window.

from cProfile import label
from pickle import FRAME
import random
import tkinter  as tk
from tkinter import BOTH, DISABLED, LEFT, RIGHT, VERTICAL, Y, Frame, Label, filedialog, Text
import os
from tkinter import ttk
from tkinter.font import NORMAL
from tkinter.messagebox import YES



root = tk.Tk()
root.title('guesser')

#Pelin arvonta ohjelma !


def delete():
   for child in root.children.values():
    info = child.grid_info()
    if info['column'] == 0:
        child.grid_forget()


def arvonta():
    global label
    list1 = []
    lista = ["Valorant","Rainbow","Vampire: The masquerade","Playerunknown's battlegrounds","Fortnite","Left 4 Dead 2","Counter strike Global offensive","Realm roayale","Black ops 1 zombies/multiplayer","Black ops 2 zombies/multiplayer","Black ops 3 zombies/multiplayer"]
    numero = random.randint(0, 10)
    hahmo  = (lista[numero])
    list1.append(hahmo)
    for app in list1:
        label = tk.Label(frame, text=app, bg="red",font=('Helvetica',20))
        label.pack()

def valorant():
    list2 = []
    lista2 = ["Brimstone","Viper","Omen","Killjoy","Cypher","Sova","Sage","phoenix","Jett","Reyna","Raze","Raze","Breach","Skye","Yoru","Astra","Kay/o","Chamber","Neon","Fade"]
    numero = random.randint(0, 19)
    randomValorantagent=(lista2[numero])
    list2.append(randomValorantagent)
    for app in list2:
        label = tk.Label(frame, text=app, bg="red",font=('Helvetica',20))
        label.pack()


def quitter():
    quit()


canvas = tk.Canvas(root,height=700,width=700,bg="#263D42")
canvas.pack(side=LEFT,fill=BOTH,expand=1)

frame = tk.Frame(root,bg="green")
frame.place(relwidth=0.8,relheight=0.8,relx=0.1,rely=0.1)
frame.pack(fill=BOTH,expand=1)

my_scrollbar = ttk.Scrollbar(frame, orient=VERTICAL, command=canvas.yview)
my_scrollbar.pack(side=RIGHT, fill=Y)


# Configure The Canvas
canvas.configure(yscrollcommand=my_scrollbar.set)
canvas.bind('<Configure>', lambda e: canvas.configure(scrollregion = canvas.bbox("all")))

# Create ANOTHER Frame INSIDE the Canvas
second_frame = Frame(canvas)

# Add that New frame To a Window In The Canvas
canvas.create_window((0,0), window=second_frame, anchor="nw")



#rlls the game
openfile = tk.Button(second_frame,text="Roll a game",padx=10,pady=5,fg="white",bg="#263D42", command=arvonta)  

openfile.pack()

#rolls a valorant agent
valorantA = tk.Button(second_frame,text='Roll valorant agent',padx=10,pady=5,fg="white",bg="#263D42",command=valorant)

valorantA.pack()

# stops program
stop = tk.Button(second_frame,text="Quit",padx=10,pady=5,fg="white",bg="#263D42",command=quitter)

stop.pack()

# deletes all info from screen.
deletor = tk.Button(second_frame,text="delete info",padx=10,pady=5,fg="white",bg="#263D42",command=delete)

deletor.pack()


root.mainloop()```
1 Answers

The following does most of what you want. I wrote it some time ago to test Scrollbars because they are wonky IMHO

from tkinter import *
from functools import partial

class ButtonsTest:
   def __init__(self):
      self.top = Tk()
      self.top.title("Click a button to remove")
      self.top.geometry("425x200+50+50")
      Label(self.top, text=" Click a button to remove it ",
            bg="lightyellow", font=('DejaVuSansMono', 12)
            ).grid(row=0, sticky="nsew")

      Button(self.top, text='Exit', bg="orange", width=9,
             command=self.top.quit).grid(row=1,column=0, 
             sticky="nsew")

      self.add_scrollbar()
      self.button_dic = {}
      self.buttons()

      self.top.mainloop()
   ##-------------------------------------------------------------------         
   def add_scrollbar(self):
        self.canv = Canvas(self.top, relief=SUNKEN)
        self.canv.config(width=400, height=200)                
        self.top_frame = Frame(self.canv, height=100)

        ##---------- scrollregion has to be larger than canvas size
        ##           otherwise it just stays in the visible canvas
        self.canv.config(scrollregion=(0,0, 400, 500))         
        self.canv.config(highlightthickness=0)                 

        ybar = Scrollbar(self.top, width=15, troughcolor="lightblue")
        ybar.config(command=self.canv.yview)                   
        ## connect the two widgets together
        self.canv.config(yscrollcommand=ybar.set)              
        ybar.grid(row=3, column=2, sticky="ns")                     
        self.canv.grid(row=3, column=0)       
        self.canv.create_window(1,0, anchor=NW, 
               window=self.top_frame)


##-------------------------------------------------------------------         
   def buttons(self):
      b_row=1
      b_col=0
      for but_num in range(1, 51):
         ## create a button and send the button's number to
         ## self.cb_handler when the button is pressed
         b = Button(self.top_frame, text = str(but_num), width=5,
                    command=partial(self.cb_handler, but_num))
         b.grid(row=b_row, column=b_col)
         ## dictionary key=button number --> button instance
         self.button_dic[but_num] = b

         b_col += 1
         if b_col > 4:
            b_col = 0
            b_row += 1

   ##----------------------------------------------------------------
   def cb_handler( self, cb_number ):
      print("\ncb_handler", cb_number)
      self.button_dic[cb_number].grid_forget()

##===================================================================
BT=ButtonsTest()
Related