python - 使用 for 循环创建多个 Tkinter 页面
问题描述
我正在创建一个包含很多页面的 Tkinter GUI。它们中的许多具有不同数据库的相同显示。
我想在数据库列表之后创建多个页面
我在名为 Databases 的列表中有一个 pandas 数据框列表,我想创建自动适合数据库的页面
global Pages
Pages=[]
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
Pages_List=[Studies_List]+Pages
self.frames = {}
for F in Pages_List: #dont forget to add the different pages
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(Studies_Page)
def show_frame(self, c):
frame = self.frames[c]
frame.tkraise()
class Studies_Page(tk.Frame): #Should, from each Site, show only the XRays corresponding to this Site. Plots sheet is an option too.
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent,background=bg_color)
self.controller=controller
tk.Label(self, text="Home > Studies ",bg=bg_color,font=('Arial',9,'italic')).pack(side='top')
label = tk.Label(self, text="Choose the Study you want the data from :",bg=bg_color, font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
Studies_frame=tk.Frame(self,bg=bg_color)
############ Studies Buttons
for i in range(len(Databases)):
tk.Button(Studies_frame, text=Pages[i]['Study'][0],command=lambda: controller.show_frame(Pages[i])).pack(in_=Studies_frame)
tk.Label(Studies_frame, text=" ",bg=bg_color,font=('Arial',11,)).pack()
Studies_frame.pack(expand=True,side='top')
for i in range(len(Databases)):
class page(tk.Frame):
def __init__(self,parent,controller):
tk.Frame.__init__(self,parent)
self.controller=controller
df=Databases[i]
f=tk.Frame(self)
f.pack()
self.table=pt=Table(f,dataframe=df)
pt.show()
return
Pages.append(page)
if __name__ == "__main__":
app = SampleApp()
app.title("X-Rays App")
app.mainloop()
这是特别需要的,因为我在起始页中有多个按钮,每个按钮都通向一个数据库。我期待每个数据库都有一个页面,但每次出现的页面列表都返回了最后一个列表。
我有很多页面要使用 tkinter 创建,它们有很多共同点,所以我想以动态的方式将列表与类一起使用,但我没有找到方法。我每次都尝试更改类名,但它仍然返回数据库列表的最后一个数据库
解决方案
没有理由class Page(tk.Frame):
在 for 循环中重新定义多次。
您可能应该做的是在循环内创建该类的实例。
也许是这样的:
class Page(tk.Frame):
def __init__(self, parent, controller, db_index):
tk.Frame.__init__(self, parent)
self.controller=controller
self.db_index = db_index
df = Databases[self.db_index]
self.pack()
self.table = Table(f, dataframe=df)
pt.show()
pages = []
for idx in range(len(database_collection)):
pages.append(Page(parent, controller, idx)) # create an instance of Page
推荐阅读
- python - With 语句的异常未传递给自定义上下文管理器 __exit__
- python - 仅在 HTML 文件中的特定单词之后抓取部分文本
- autodesk-forge - Forge 应用程序可以在 localhost 上运行,但无法在浏览器中加载结果
- javascript - 如何格式化 JavaScript 生成的 HTML 代码?
- asp.net-core - MassTransit 多总线或单总线
- swift - 自定义 NavigationbarButtonItem 显示在错误的位置
- mysql - 如何避免mysql连接查询中的全表扫描
- javascript - 即使返回新的状态对象,Redux 也不会更新组件
- reactjs - 在反应传单中向多边形添加弹出窗口
- angular - Web 组件中的 ng-content 有什么问题?