Как обновить self.variables в классе из другого класса, запущенного в другом потоке - PullRequest
0 голосов
/ 27 июня 2019

Я пытаюсь обновить self.variables данного класса, работающего в потоке (потому что у меня есть цикл while для вычисления некоторой работы), из класса пользовательского интерфейса при нажатии кнопки.Поэтому при нажатии кнопки «Сохранить» в главном окне изменения, внесенные в набор данных настроек, сохраняются в файл JSON, а переменные в другом классе обновляются для отражения изменений.


import time
import os
from threading import Thread
from tkinter import *
from tkinter import ttk


class MainWindow:  # This is UI element which houses all the settings and vectors to be modified
    def __init__(self, top, settings, vectors):
        self.top = top
        self.top.resizable(0, 0)

        self.settings = settings
        self.vectors = vectors

        self.Btn_4_2 = ttk.Button(top)
        self.Btn_4_2.place(height=25, width=50)
        self.Btn_4_2.configure(text='''Save''')
        self.Btn_4_2.configure(command=self.Btn_4_2_Fun)

    def Btn_4_2_Fun(self):  # this button is used to save the modification to the json file
        database_save(self.settings, self.vectors)
       # Dataset.constructure()  # update the self variables in the Dataset class to reflect the changes made in the UI
        return

class Dataset:

    def __init__(self, settings, vectors):
        self.vec_1 = None
        self.vec_2 = None

        self.constructure(settings, vectors)  # Assign all required variables using this method

        self.core()  # Run the While loop to do the required computation
        return

    def constructure(self, settings, vectors):
        self.vec_1 = settings[0]
        self.vec_2 = vectors[2]
        return

    def core(self):
        while True:
            time.sleep(0.1)
            if self.vec_1 == 6:
                print("problem")
            elif self.vec_2 == 10:
                print("found")
        retrun


def database_read():

    settings = [1,2,3,4,5,6,7,8,9,10]

    vectors = [10,9,8,7,6,5,4,3,2,1]

    return settings, vectors

def database_save(settings, vectors):

    print(settings, vectors)

    return

def main():

    settings, vectors = database_read() # returns the databases stored in a json file

    # UI Declaration
    root = Tk()
    Main = MainWindow(root, settings, vectors)

    #Dataset reader thread
    A_thread = Thread(target=Dataset, args=[settings, vectors])
    A_thread.setDaemon(True)
    A_thread.start()

    # UI Start
    root.mainloop()
    os._exit(1)
    return

main()

Мое рабочее решениеЧтобы решить эту проблему, нужно превратить метод «конструктор» в @classmethod и вместо этого объявить необходимые переменные в переменные класса.Но я не уверен, что это хорошее решение

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...