如何识别sqlite数据库表的名称ttk.Treeview从中加载数据



我有一个用python3编写的tkinter应用程序。它有一个主tk.Frame。使用for循环,我在那里构建了两个ttk.LabelFrame,然后每个帧都得到它的ttk.Treeview。这些树视图中的每一个都从不同的表(名为aliens1aliens2(加载数据:

class Application:
def __init__(self, master):
self.master = master

self.database = Database(self.master, self)
self.turns_frame = TurnsFrame(self.master, self)
class TurnsFrame:
def __init__(self, master, app):
self.master = master
self.app = app
self.frame = tk.Frame(self.master, bd=2)

# Create LabelFrames and their Treeviews
for i in range(3):
ap_frame = tk.LabelFrame(self.frame, text="Alien Player {}".format(str(i+1)))
ap_frame.grid(row=0, column=i)
tv = tk.ttk.Treeview(ap_frame,
columns=tuple(range(1, 12)),
show="headings",
height=30)
tv.pack()
... creating columns ...
# Create rows
with self.app.database.db:
self.app.database.cursor.execute("SELECT turn, econ_rolls, econ_rolls_extra, cp_fleet, "
"cp_tech, cp_def, fleet_launch, roll_econ, roll_fleet, "
"roll_tech, roll_def FROM aliens{}".format(str(i+1)))
rows = self.app.database.cursor.fetchall()
for r in rows:
tv.insert("", "end", values=r)
# Bind row double-click
tv.bind("<Double-1>", self.get_turn_number)
def get_turn_number(self, event):
item_id = event.widget.focus()
item = event.widget.item(item_id)
values = item["values"]
turn_id = values[0]
print("Turn: ", turn_id)
return turn_id
class Database:
def __init__(self, master, app):
self.master = master
self.app = app
self.folder = os.path.dirname(os.path.abspath(__file__))
self.db = self.create_connection(self.folder)
self.cursor = self.db.cursor()
def create_connection(self, f):
db = None
try:
db = sqlite3.connect(os.path.join(f, "aliens.db"))
except sqlite3.Error as e:
print(e)
return db
def initialize_tables(self, nr):
# SOME OTHER FRAME CALLS THIS FUNCTION AND GIVES THE VARIABLE 'nr'
with self.db:
for i in range(1, nr+1):
# print("Creating table aliens{}".format(str(i)))
self.cursor.execute("CREATE TABLE aliens{}(".format(i) +
"turn INTEGER PRIMARY KEY,"
"econ_rolls INTEGER,"
"econ_rolls_extra INTEGER,"
"cp_fleet INTEGER,"
"cp_tech INTEGER,"
"cp_def INTEGER,"
"fleet_launch STRING,"
"roll_econ STRING,"
"roll_fleet STRING,"
"roll_tech STRING,"
"roll_def STRING)")
def main():
root = tk.Tk()
main_app = Application(root)
root.mainloop()
if __name__ == "__main__":
main()

它看起来很好,工作也很好,看起来像这样应用

现在我可以双击任何一行,它就会执行self.get_turn_number。太棒了为了进一步的工作,我需要获得它从中加载行的数据库表名(取决于我双击的树视图-第一个外星人玩家1或第二个外星人玩家2(。外星人玩家1从表alien1加载数据,玩家2从aliens2中加载数据。

我搜索了文档,但在ttk.Treeview中没有发现任何与此相关的内容。以前似乎没有人遇到过这种问题。有办法做到这一点吗?

我刚刚注意到你所在的for循环。你可以做的是将数字传递给函数,然后运行它,比如:

.... # Same code
tv.bind("<Double-1>", lambda e,num=i: self.calculate_econ_phase(num)
def calculate_econ_phase(self,num):
print(f'Alien{num}')

作为答案发布,因为评论太长。

相关内容

  • 没有找到相关文章

最新更新