Home > Enterprise >  How can i insert a list of buttons into text with a scrollbar?
How can i insert a list of buttons into text with a scrollbar?

Time:04-09

I'm a student coder. I would like to create a list of buttons. However there are too many buttons to fit onto a single screen. I have tried to incorporate a scrollbar, however the buttons do not go inside the textbox, even after setting the window to 'text'.

Here's what ive tried:

from tkinter import *

root = Tk()
root.title('Scrollbar text box')
root.geometry("600x500")




#my exercise list

FullExerciseList = [
    "Abdominal Crunches", 
    "Russian Twist",
    "Mountain Climber",
    "Heel Touch" ,
    "Leg Raises",
    "Plank",
    "Cobra Stretch",
    "Arm Raises",
    "Side Arm Raises",
    "Tricep Dips",
    "Arm Circles Clockwise",
    "Arm Circles Counter Clockwise",
    "Diamond Push Ups",
    "Jumping Jacks" ,
    "Chest Press Pulse",
    "Push Ups" ,
    "Wall Push Ups",
    "Triceps Stretch Left" ,
    "Tricep Stretch Right",
    "Cross Arm Stretch" ,
    "Rhomboid Pulls",
    "Knee Push Ups",
    "Arm Scissors",
    "Cat Cow Pose",
    "Child Pose",
    "Incline Push Ups",
    "Wide Arm Push Ups",
    "Box Push Ups",
    "Hindu Push Ups",
    "Side Hop",
    "Squats",
    "Side Lying Lift Left",
    "Side Lying Lift Right",
    "Backward Lunge",
    "Donkey Kicks Right",
    "Donkey Kick Left",
    "Left Quad Stretch",
    "Right Quad Stretch",
    "Wall Calf Raises"
    ]


#def yview function

def multiple_yview(*args):
    my_text1.yview(*args)
    my_text1.yview(*args)
    



#frame

my_frame = Frame(root)
my_frame.pack(pady=20)



#scrollbar

text_scroll = Scrollbar(my_frame)
text_scroll.pack(side = RIGHT, fill = Y)



my_text1 = Text(my_frame, width = 20, height =25, font = ("Helvetica", 16), yscrollcommand = text_scroll, wrap = 'none')
my_text1.pack(side=RIGHT, padx=5)

for item in FullExerciseList:
    button = Button(my_frame, text=item)
    button.pack()
    
#configuring scroll bar

text_scroll.config(command = multiple_yview)


root.mainloop()

This has been a persistent issue! Thanks for any help in advance

CodePudding user response:

First you need to use my_text1 as the parent of those buttons if you want to put them into my_text1.

Second you need to use my_text1.window_create(...) instead of .pack() to put those button into my_text1.

Final yscrollcommand = text_scroll should be yscrollcommand = text_scroll.set instead.

# changed yscrollcommand=text_scroll to yscrollcommand=text_scroll.set
my_text1 = Text(my_frame, width=20, height=25, font=("Helvetica", 16), yscrollcommand=text_scroll.set, wrap='none')
my_text1.pack(side=RIGHT, padx=5)

for item in FullExerciseList:
    button = Button(my_text1, text=item) # use my_text1 as parent
    # insert the button into my_text1
    my_text1.window_create('end', window=button)
    # add a newline so that each button is in a separate line
    my_text1.insert('end', '\n')
  • Related