Использование экземпляров из основного модуля в других модулях в Python - PullRequest
0 голосов
/ 26 января 2020

В настоящее время я реструктурирую свой код с помощью модулей и сталкиваюсь с проблемой, связанной с экземплярами.

На данный момент я создал 3 сценария: main_script.py, launch gui .py, steppermotors.py.

main_script должен создавать только экземпляры для запуска GUI и инициализации конфигурации шагового двигателя и т. Д. c.

Поскольку мне нужен экземпляр GUI запуска gui .Launch Gui также в Метод класса StepperMotor Я думал, что смогу просто создать экземпляр так же, как в основном скрипте. Мне также нужен экземпляр StepperMotors (), чтобы вызвать метод "Calculate_angle ()" в классе Launch Gui.

К сожалению, GUI больше не запускается при создании одинаковых экземпляров в каждом модуль, и я также не получаю никаких сообщений об ошибках. Кроме того, я думаю, что это не совсем лучшая практика.

Поэтому я хотел спросить, существует ли «правильный» и работающий способ обмена экземплярами с другими модулями, которые были созданы только в основном сценарии?

Надеюсь, вы поможете мне с этим!

См. Фрагменты кода затронутых модулей ниже:

main_script.py

import launchgui
import steppermotors
from tkinter import *

def main():
  root = Tk()
  gui = launchgui.LaunchGui(root)                                       #Creates instance 'gui' of the class 'LaunchGui' from the module 'launchgui' & initialises class    
  stepper = steppermotors.StepperMotors()                               #Creates instance 'stepper' of the class 'StepperMotors' from the module 'steppermotors' & initialises class
  root.mainloop()                                                       #Mainloop for tkinter-GUI
  ...

запуск gui .py

#own modules
import steppermotors
#other modules
from tkinter import *

class LaunchGui:

   def __init__(self, root):
       ''' This function creates the gui with all buttons etc. 
           when initialising this class
       '''

       #Instances
       stepper = steppermotors.StepperMotors()  

       ...(Gui buttons etc. here)
       #Move to Position 
       btn_moveto_position = Button(control_frame, text='Move to Position', command=lambda:stepper.calculate_angle([0,0,0,0]))
       ...

steppermotors.py

#own modules
import launchgui
#other modules 
from tkinter import *

class StepperMotors:
''' This class contains the configuration and control algorithms for 
    the stepper motors (Axis1-4)
'''
    def __init__(self):                                                         
    ''' Setting Output-Pins, Microstep-Resolution, Transmission and
        Ramping parameters for the different motors when 
        initialising the class
    '''

    #Instances of other classes 
    root = Tk()
    gui = launchgui.LaunchGui(root)                                 #Creates instance 'gui' of the class 'LaunchGui' from the module 'launchgui'

    ...(some other functions here)

    def calculate_angle(self, previous_angles_list):
    ''' This function calculates the difference (=delta) between
        the current and previous slider_values (=angle)
    '''
    #Current angles 
    current_angles_list = []                                        #Creates empty list to append current values
    delta_angles_list = []                                          #Creates empty list to append difference between current and previous angles (=delta)

    for idx in range(self.number_of_motors):                            #Looping through list indices (idx)
        current_angles_list.append(gui.SLIDER_list[idx].get())      #Appends currently selected slidervalues (=current angle) to current_angles_list
        deltas_list.append(int(current_angles_list[idx] -       
                                previous_angles_list[idx]))         #Calculates the difference between current and previous angle as an integer and appends it to delta list
...