如何将按钮列表插入带有滚动条的文本中?

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

我是一名学生程序员。我想创建一个按钮列表。但是,按钮太多,无法放在一个屏幕上。我试图合并一个滚动条,但是按钮不会进入文本框,即使在将 window 设置为 'text' 之后也是如此。

这是我尝试过的:

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()

这是一个长期存在的问题!提前感谢您的帮助

首先,如果要将它们放入 my_text1,您需要使用 my_text1 作为这些按钮的父级。

其次,您需要使用 my_text1.window_create(...) 而不是 .pack() 将这些按钮放入 my_text1

最终 yscrollcommand = text_scroll 应该是 yscrollcommand = text_scroll.set

# 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')