![](/img/trans.png)
[英]How to call another python script from a .py file in a new window
[英]How to call modules from another .py file
第一次发帖!
我对 python (和编程)相当陌生。 我已经开始制作一个基本的 tkinter 程序,代码现在变得很长。 我想在不同的.py文件之间拆分它以使其更易于导航,到目前为止,我所有的代码都存在于类中,将主要的window与计算函数分开。 二级windows等。
第一个问题,这样拆分代码是否被认为是一种好习惯? 我觉得是,但想确定!
其次,如何处理文件之间的模块的最佳方式是什么?
例如,我在 main_window.py 文件中导入了 tkinter 和 matplotlib。 I have the main_window class function which calls a different class which I want to move to another file, but this secondary class has a line which calls tkinter. 我想通过辅助 function 传递 self ,以便它使用相同的实例。
这是一个示例代码来说明。 第一个文件 main_window.py:
# main_window.py
import tkinter as tk
import matplotlib
import matplotlib.pyplot as plt
import app_design # app_design.py contains the code I want to break out
class MainWindow:
def __intit__(self, root):
self.root = root
self.start_gui()
def start_gui(self):
# a bunch of code
...
# in reality this is read from a program file on startup
color_mode = "Dark"
# This is just an example, the matplotlib call in the other app is in the __init__
self.bg_col_mode = tk.StringVar()
self.bg_col_mode.set(app_design.AppColors(color_mode).background())
# a bucnh more code of various tk widgets and matplotlib charts
...
if __name__ == '__main__':
app = MainWindow(tk.Tk())
app.root.mainloop()
然后是我想拆分的一些代码示例。 这不是 class 引用 MainWindow class 外部模块的唯一实例,但它可以作为示例:
# app_design.py
class AppColors:
def __init__(self, color_mode):
self.color_mode = color_mode
if self.col_mode == "Dark":
self.plt.style.use("Dark") # it is this .plt call that has moved from the main_window.py file to the new file
else:
self.plt.style.use("Light")
def background_mode(self):
if self.color_mode == "Dark":
return "#292929" # colour code
else:
return "#F8F1F1"
第一个问题,这样拆分代码是否被认为是一种好习惯? 我觉得是,但想确定!
我其实不了解自己,我只有后端的代码。
其次,如何处理文件之间的模块的最佳方式是什么?
您只需导入文件(或直接导入 function)。
def hello(name):
print("Hello ", name)
from file1 import hello
hello("arjix")
这样就可以直接使用 function 你好
或者
import .file1
file1.hello("arjix")
PS:确保这两个文件在同一个文件夹中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.