我在使用某些代码时遇到了麻烦,我想在屏幕上滚动一组小部件,但滚动条无法正常工作。我已经附上了结果的图片和下面的代码,我使用的是python tkinter,namesfile.txt仅包含人员列表。
tkinter import *
Y_level=10
people = []
f = open("namefile.txt", "r")
for people_in_file in f:
people.append(people_in_file)
parent = Tk()
canvas = Canvas(parent)
scroll_y = Scrollbar(parent, orient="vertical", command=canvas.yview)
frame = Frame(canvas)
for person in people:
label_name='person: '+person
print(label_name)
print(Y_level)
label_name = Label(parent, text=person)
label_name.place(x=10, y=Y_level)
Y_level=Y_level+20
canvas.create_window(0, 0, anchor='nw', window=frame)
canvas.update_idletasks()
canvas.configure(scrollregion=canvas.bbox('all'),
yscrollcommand=scroll_y.set)
canvas.pack(fill='both', expand=True, side='left')
scroll_y.pack(fill='y', side='right')
parent.mainloop()
答案 0 :(得分:0)
首先,您应该将标签放在frame
而不是parent
内。其次,您应该使用pack()
而不是place()
,因为place()
不会扩展父容器。
for person in people:
label_name='person: '+person
print(label_name)
label_name = Label(frame, text=person)
label_name.pack()