在自定义TKinter可滚动框架中添加文本或标签

0 投票
1 回答
37 浏览
提问于 2025-04-13 19:24

抱歉,这是我第一次提问!!!

我想在一个自定义的 可滚动框架 中添加一份名字列表。目前我正在使用 CTkLabel 来显示这些名字。

import customtkinter
list_names = ["Liam", "Olivia", "Noah", "Emma"]
root = customtkinter.CTk()
root.geometry("1000x550")
root.title("Test")
frame = customtkinter.CTkFrame(master=root)
frame.pack(pady=20, padx=60, fill="both", expand=True)
other_frame = customtkinter.CTkScrollableFrame(master=frame, height=350, width=250, label_text="List").pack(pady=40)
for name in list_names:
        customtkinter.CTkLabel(master=other_frame, text=name).pack(pady=10)
root.mainloop()

这是我运行代码时发生的情况,名字没有出现在可滚动框架里

1 个回答

1

你代码的问题出在第12行(当你定义other_frame的时候)。在这一行,你同时创建了一个框架并把它放入了界面中。但是因为你把这两件事放在了一行里,所以other_frame这个变量实际上保存的是.pack()方法的返回值(在这种情况下是None)。

要让你的代码正常工作,你应该把第12行替换成这样:

other_frame = customtkinter.CTkScrollableFrame(master=frame, height=350, width=250, label_text="List")
other_frame.pack(pady=40)

现在完整的代码是:

import customtkinter

list_names = ["Liam", "Olivia", "Noah", "Emma"]

root = customtkinter.CTk()
root.geometry("1000x550")
root.title("Test")

frame = customtkinter.CTkFrame(master=root)
frame.pack(pady=20, padx=60, fill="both", expand=True)

other_frame = customtkinter.CTkScrollableFrame(master=frame, height=350, width=250, label_text="List")
other_frame.pack(pady=40)

for name in list_names:
        customtkinter.CTkLabel(master=other_frame, text=name).pack(pady=10)

root.mainloop()

希望我能帮到你,祝你有个愉快的一天。

PS:你不需要为提问而感到抱歉;)

撰写回答