[英]Not clear about how to organize Python code with multiple functions as separate files
[英]How to organize Tkinter code with many windows and functions
我正在使用Python和Tkinter构建一个数据分析程序,该程序允许输入,打印和导出数据(一种Excel克隆)。 它实现了许多需要访问和修改共享数据变量的窗口和功能。 我应该如何组织GUI以确保每个窗口都可以来回传输数据,同时还要分隔代码以能够独立修改和调试每个功能?
最初,我建立了一个带有子功能的主GUI类(示例1),由于所有变量都是通过self共享的,因此所有功能很容易修改和访问初始化的数据。 但是,随着我越来越多地修改代码(实际上是数千行),由于代码的划分不正确,调试变得非常困难。
我看到一个建议,使每个窗口(即数据表,绘图窗口等)成为独立的类(示例2),但是我想出了如何在类之间传递数据的唯一方法(将第一个窗口对象传递给其他窗口) )看起来非常混乱,我唯一能想到的选择是在定义/调用时将所有必需的变量显式传递给每个窗口,这也可能非常混乱。
class GUI:
def __init__(self, toptk):
self.toptk = toptk
""" Code creating main window and toolbar """
list_x = []
list_y = []
""" Code adding data """
def entryTable(self):
tablewin = Toplevel(self.toptk)
""" Code creating frames, buttons, etc """
""" Code doing something to list_x, list_y """
def plotWin(self):
plotwin = Toplevel(self.toptk)
""" Code creating frames, buttons, etc """
""" Code doing something to list_x, list_y """
entryTable()
plotWin()
root = tk.Tk()
main = GUI(root)
root.mainloop()
class GUI:
def __init__(self, toptk):
""" Code creating main window and toolbar """
list_x = []
list_y = []
""" Code adding data """
entryTable.__init__(toptk,self)
plotWin.__init__(toptk,self)
class entryTable():
def __init__(self,toptk,topGUI):
tabletop = Toplevel(toptk)
""" Code creating frames, buttons, etc """
""" Code doing something to topGUI.list_x, topGUI.list_y """
class plotWin():
def __init__(self,toptk,topGUI):
plottop = Toplevel(toptk)
""" Code creating frames, buttons, etc """
""" Code doing something to topGUI.list_x, topGUI.list_y """
如何在保留类之间简单的变量交换的同时还允许我分别隔离和调试每个多窗口程序的方式来改进此多窗口程序的组织?
非常感谢你。
问题 :如何在类之间传递数据
该解决方案不通过任何高炮类,它简单的采用了全球 class DATA
对象。 也可以将此对象保存在自己的DATA.py
,以import DATA
。
import tkinter as tk
class DATA:
""" Data container """
list_x = []
list_y = []
class EntryTable(tk.Toplevel):
def __init__(self, parent):
super().__init__(parent)
""" Code creating frames, buttons, etc """
""" Code adding something to DATA.list_x, DATA.list_y """
DATA.list_x = [1, 2, 3]
DATA.list_y = [4, 5, 6]
class PlotWin(tk.Toplevel):
def __init__(self, parent):
super().__init__(parent)
""" Code creating frames, buttons, etc """
""" Code doing something with DATA.list_x, DATA.list_y """
print('plot:{}'.format((DATA.list_x, DATA.list_y)))
class App(tk.Tk):
def __init__(self):
super().__init__()
""" Code adding main window widgets and toolbar """
""" Code adding Toplevel window's """
entryTable = EntryTable(self)
plotWin = PlotWin(self)
if __name__ == '__main__':
App().mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.