Как установить текст в другом окне
Делаю IDE на Python с помощью PyQt5.
Когда я нажимаю кнопку Run
, то путь, который находится снизу программы прилетает в QProcess
и идет запуск этого файла, то есть запуск кода в этом файле.
Когда я нажимаю кнопку New File
, то срабатывает функция new_file
, в которой вызывается новое окно. В этом окне пользователь вводит название файла и нажимает кнопку Create
.
После создания окно закрывается и, по идее, путь должен прилетать в label
, который находится снизу программы (из этого label
берет путь qprocess
для запуска файла). Но у меня он не прилетает, потому что я не знаю как сделать так, чтобы из функции одного класса присвоить текст атрибуту другого класса.
В классе Cnf_Window есть функция create_new_file
. В ней нужно присвоить путь path_of_the_current_file_label_bottom
, который находится в MainWindow
после создания файла: path_of_the_current_file_label_bottom.setText(path)
Как это сделать?
Прикрепил код:
class CnfWindow(QtWidgets.QMainWindow, Ui_CNFWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.setWindowTitle("CNFWindow")
self.button_confirm_create_new_file.clicked.connect(
self.create_new_file)
def create_new_file(self):
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
open(f"{path}\\{self.name_of_new_file_input_window.text()}.py",
"a").close()
self.hide()
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.setWindowTitle("IDE")
self.process = None
self.new_window = None
self.code_entry_window.setDisabled(True)
self.timer = QtCore.QTime()
self.result_of_program_execution_window.hide()
self.button_new_file.triggered.connect(self.new_file)
self.button_open_file.triggered.connect(self.open_file)
self.button_save_as.triggered.connect(self.save_as_file)
self.button_run.triggered.connect(self.run_code)
self.button_stop.triggered.connect(self.stop_code)
self.button_save.triggered.connect(self.save_file)
self.button_new_window.triggered.connect(self.create_new_window)
self.button_close_window.triggered.connect(self.close_new_window)
self.button_exit.triggered.connect(self.exit_the_program)
self.button_hide_result_window.triggered.connect(self.hide_result_window)
self.cfn_window = CnfWindow()
# -------------------------- BEGIN MENU <FILE> ----------------------------
def new_file(self):
self.cfn_window.name_of_new_file_input_window.clear() # +++
self.cfn_window.show()
self.code_entry_window.setDisabled(False)
# self.code_entry_window.setDisabled(False)
# cfn_window.hide()
def open_file(self):
path = QFileDialog.getOpenFileName(self, "Save file", "",
"All files (*.*)")[0]
if path:
try:
with open(path, "r") as file:
self.code_entry_window.setPlainText(file.read())
except Exception as e:
QtWidgets.QErrorMessage().showMessage(str(e))
self.code_entry_window.setDisabled(False)
self.path_of_the_current_file_label_bottom.setText(path)
def save_file(self):
try:
with open(f"{self.path_of_the_current_file_label_bottom.text()}", "w") as save_file:
save_file.write(self.code_entry_window.toPlainText())
except IOError:
pass
def save_as_file(self):
path = QFileDialog.getSaveFileName(self, "Open file", "",
"All files (*.*)")[0]
if path:
try:
with open(path, "w") as file:
text_on_current_file = self.code_entry_window.toPlainText()
file.write(text_on_current_file)
except Exception as e:
QtWidgets.QErrorMessage().showMessage(str(e))
self.path_of_the_current_file_label_bottom.setText(path)
def create_new_window(self):
if self.new_window is None:
self.new_window = MainWindow()
self.new_window.show()
else:
self.new_window.close()
self.new_window = None
def close_new_window(self):
self.new_window.close()
self.new_window = None
def exit_the_program(self):
self.close()
# -------------------------- END MENU <FILE> ------------------------------
# --------------------------- BEGIN MENU <RUN> ----------------------------
def message(self, string):
self.result_of_program_execution_window.append(string)
def run_code(self):
self.save_file()
self.result_of_program_execution_window.show()
self.result_of_program_execution_window.clear()
if self.process is None: # No process running.
self.message("[Started]\n")
self.process = QProcess()
self.process.readyReadStandardOutput.connect(self.handle_stdout)
self.process.readyReadStandardError.connect(self.handle_stderr)
self.process.started.connect(self.timer.start)
self.process.finished.connect(self.finished_code)
self.process.start("python", [f"{self.path_of_the_current_file_label_bottom.text()}"])
def handle_stderr(self):
data = self.process.readAllStandardError()
stderr = bytes(data).decode("utf8")
self.message(stderr)
def handle_stdout(self):
data = self.process.readAllStandardOutput()
stdout = bytes(data).decode("utf8")
self.message(stdout)
def finished_code(self):
procTime = self.timer.elapsed()
self.message(f"[Finished in {procTime / 1000}s]")
self.process = None
# TODO: Try/Except на процесс (при втором нажатии вылетает ошибка)
def stop_code(self):
self.process.kill()
# -------------------------- END MENU <RUN> -------------------------------
# Program closure processing
def closeEvent(self, event):
self.save_file()
reply = QMessageBox.question(self, 'Window Close',
'Are you sure you want to close the window?',
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No)
if reply == QMessageBox.Yes:
event.accept()
else:
event.ignore()
def hide_result_window(self):
self.result_of_program_execution_window.hide()
if __name__ == "__main__":
application = QtWidgets.QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(application.exec_())
Ответы (1 шт):
Пожалуйста всегда публикуйте минимально-воспроизводимый пример, который включает все модули для запуска приложения. Импорты также показывайте.
import sys # <<<<<
import inspect # <<<<<
import os.path # <<<<<
from pathlib import Path # <<<<<
from PyQt5 import QtCore, QtGui, QtWidgets # <<<<<
from PyQt5.Qt import * # <<<<<
from create_new_file_window import Ui_CNFWindow # <<<<<
from ide_ui import Ui_MainWindow # <<<<<
class CnfWindow(QtWidgets.QMainWindow, Ui_CNFWindow):
def __init__(self, parent):
super().__init__()
self.setupUi(self)
self.setWindowTitle("CNFWindow")
self.path = None # <<<<<
self.parent = parent # <<<<<
self.button_confirm_create_new_file.clicked.connect(
self.create_new_file)
def create_new_file(self):
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
self.path = f"{path}\\{self.name_of_new_file_input_window.text()}.py" # <<<<<
open(self.path, "a").close() # <<<<<
self.parent.path_of_the_current_file_label_bottom.setText(self.path) # <<<<< !!!
self.hide()
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.setWindowTitle("IDE")
self.process = None
self.new_window = None
self.code_entry_window.setDisabled(True)
self.timer = QtCore.QTime()
self.result_of_program_execution_window.hide()
self.button_new_file.triggered.connect(self.new_file)
self.button_open_file.triggered.connect(self.open_file)
self.button_save_as.triggered.connect(self.save_as_file)
self.button_run.triggered.connect(self.run_code)
self.button_stop.triggered.connect(self.stop_code)
self.button_save.triggered.connect(self.save_file)
self.button_new_window.triggered.connect(self.create_new_window)
self.button_close_window.triggered.connect(self.close_new_window)
self.button_exit.triggered.connect(self.exit_the_program)
###
# ? self.button_hide_result_window.triggered.connect(self.hide_result_window)
self.cfn_window = CnfWindow(self) # <<< + self
# -------------------------- BEGIN MENU <FILE> ----------------------------
def new_file(self):
self.cfn_window.name_of_new_file_input_window.clear() # +++
self.cfn_window.show()
self.code_entry_window.setDisabled(False)
# self.code_entry_window.setDisabled(False)
# cfn_window.hide()
self.path_of_the_current_file_label_bottom.setText('BEGIN MENU <FILE>: New File') # <<<<<
def open_file(self):
path = QFileDialog.getOpenFileName(self, "Save file", "",
"All files (*.*)")[0]
if path:
try:
with open(path, "r") as file:
self.code_entry_window.setPlainText(file.read())
except Exception as e:
QtWidgets.QErrorMessage().showMessage(str(e))
self.code_entry_window.setDisabled(False)
self.path_of_the_current_file_label_bottom.setText(path)
def save_file(self):
try:
with open(f"{self.path_of_the_current_file_label_bottom.text()}", "w") as save_file:
save_file.write(self.code_entry_window.toPlainText())
except IOError:
pass
def save_as_file(self):
path = QFileDialog.getSaveFileName(self, "Open file", "",
"All files (*.*)")[0]
if path:
try:
with open(path, "w") as file:
text_on_current_file = self.code_entry_window.toPlainText()
file.write(text_on_current_file)
except Exception as e:
QtWidgets.QErrorMessage().showMessage(str(e))
self.path_of_the_current_file_label_bottom.setText(path)
def create_new_window(self):
if self.new_window is None:
self.new_window = MainWindow()
self.new_window.show()
else:
self.new_window.close()
self.new_window = None
def close_new_window(self):
self.new_window.close()
self.new_window = None
def exit_the_program(self):
self.close()
# -------------------------- END MENU <FILE> ------------------------------
# --------------------------- BEGIN MENU <RUN> ----------------------------
def message(self, string):
self.result_of_program_execution_window.append(string)
def run_code(self):
self.save_file()
self.result_of_program_execution_window.show()
self.result_of_program_execution_window.clear()
if self.process is None: # No process running.
self.message("[Started]\n")
self.process = QProcess()
self.process.readyReadStandardOutput.connect(self.handle_stdout)
self.process.readyReadStandardError.connect(self.handle_stderr)
self.process.started.connect(self.timer.start)
self.process.finished.connect(self.finished_code)
self.process.start("python", [f"{self.path_of_the_current_file_label_bottom.text()}"])
def handle_stderr(self):
data = self.process.readAllStandardError()
stderr = bytes(data).decode("utf8")
self.message(stderr)
def handle_stdout(self):
data = self.process.readAllStandardOutput()
stdout = bytes(data).decode("utf8")
self.message(stdout)
def finished_code(self):
procTime = self.timer.elapsed()
self.message(f"[Finished in {procTime / 1000}s]")
self.process = None
# TODO: Try/Except на процесс (при втором нажатии вылетает ошибка)
def stop_code(self):
self.process.kill()
# -------------------------- END MENU <RUN> -------------------------------
# Program closure processing
def closeEvent(self, event):
self.save_file()
reply = QMessageBox.question(self, 'Window Close',
'Are you sure you want to close the window?',
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No)
if reply == QMessageBox.Yes:
event.accept()
else:
event.ignore()
def hide_result_window(self):
self.result_of_program_execution_window.hide()
if __name__ == "__main__":
application = QtWidgets.QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(application.exec_())