所以,我正在尝试使用 Tkinter 为学校项目创建一个通讯录应用程序。这是它的工作原理: 用户给了我一个数据库(.db)并使用 sqlite3,你应该将它们自动放在标签中并将它们网格化到屏幕上,但是,我想从每个联系人中创建一个类,以便我可以在它们上使用一些功能。所以我尝试使用此代码创建一个类(还没有函数):
class User(Label):
def __init__(self,name, last_name, phone_number, email, id, row):
self.frame = Frame(second_frame)
self.frame.grid(row = row, column = 0)
self.id_label = Label(self.frame, text = id, font = sub_font, bg = background_color, fg = sub_font_color)
self.id_label.grid(row = row, column = 0)
self.name_label = Label(self.frame, text = name, font = sub_font, bg = background_color, fg = sub_font_color)
self.name_label.grid(row = row, column = 1)
self.last_name_label = Label(self.frame, text = last_name, font = sub_font, bg = background_color, fg = sub_font_color)
self.last_name_label.grid(row = row, column = 2)
self.phone_number_label = Label(self.frame, text = phone_number, font = sub_font, bg = background_color, fg = sub_font_color)
self.phone_number_label.grid(row = row, column = 3)
self.email_label = Label(self.frame, text = email, font = sub_font, bg = background_color, fg = sub_font_color)
self.email_label.grid(row = row, column = 4)
我对其进行了测试,一切都在我的(根)屏幕中解决了。但我想制作一个框架,这样我就可以为应用程序使用滚动条,但要实现这一点,我应该制作一个主框架(名为 second_frame)。 当我尝试在该主框架 (second_frame) 中使用它时,它不起作用并将所有变量放在第 1 列中。
这是我如何上课:
conn = sqlite3.connect("contacts_book.db")
cursor = conn.cursor()
cursor.execute("SELECT *,oid FROM contacts")
contacts = cursor.fetchall()
sub_row = design_row + 1
for contact in contacts:
cont = User(contact[0], contact[1], contact[2], contact[3], contact[4], sub_row)
sub_row += 1
conn.commit()
conn.close()
这是我制作 second_frame 的方法:
# create a main_frame
main_frame = Frame(root, bg = background_color)
main_frame.pack(fill = BOTH , expand = 1)
# create a canvas
my_canvas = Canvas(main_frame, bg = background_color)
my_canvas.pack(side = LEFT,fill = BOTH, expand = 1)
# add scrollbar to canvas
my_scrollbar = ttk.Scrollbar(main_frame , orient = VERTICAL, command = my_canvas.yview)
my_scrollbar.pack(side = RIGHT, fill = Y)
# config scrollbar
my_canvas.configure(yscrollcommand = my_scrollbar.set, bg = background_color)
my_canvas.bind("<Configure>", lambda e: my_canvas.configure(scrollregion = my_canvas.bbox("all")))
# create another frame in canvas
second_frame = Frame(my_canvas, bg = background_color)
# add that new frame in the canvas
my_canvas.create_window((0,0), window = second_frame, anchor = "nw")
我做错了什么?是因为我把它们放在 second_frame 还是什么?感谢您的帮助!