[英]Avoid circular import when accessing instance value from main.py
我是 Python 和一般編程的新手。 所以對於更有經驗的程序員來說,也許有一個簡單的解決方案。 我已經閱讀了很多關於循環導入的問題,但不幸的是,如果我不想將所有代碼移動到一個文件中,那么沒有什么可以適用於我的情況。
我使用 pyqt(qt creator)創建了一個用戶界面,並將 mainwindow.ui 轉換為 mainwindow.py。 我的計划是將代碼分成 3 個模塊。 一個啟動應用程序的主模塊,一個帶有主 window 的 class 的 ui 模塊和一個帶有按鈕類的按鈕模塊。
我的問題是按鈕類中的函數應該更改主 window 實例的 label 值。 我學會了在主模塊中創建主 window 實例。 因此,我需要將實例從主模塊導入按鈕模塊以更改預期值,這會導致循環導入。
我該如何組織/構建我的代碼以避免這種情況?
這是一個簡短的簡化示例,以便更好地理解:
主程序
import sys
from qtpy import QtWidgets
from ui import MainWindow
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())
用戶界面.py
from qtpy import QtWidgets
from userinterface.mainwindow import Ui_MainWindow
import buttons
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
QtWidgets.QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.button_0 = buttons.NumberButton(0)
self.button_1 = buttons.NumberButton(1)
self.ui.btn_0.clicked.connect(self.button_0.button_clicked)
self.ui.btn_1.clicked.connect(self.button_1.button_clicked)
按鈕.py
from main import window
class NumberButton:
def __init__(self, number):
self.number = str(number)
def button_clicked(self):
window.ui.lb_result.setText(self.number)
您的設計問題是您的NumberButton
class 調用一個特定的 window 實例。 你必須讓你的按鈕知道它們屬於哪個 window。 嘗試以下操作:從 buttons.py 中刪除 import 語句,並向__init__
方法添加一個新參數window
:
class NumberButton:
def __init__(self, window, number):
self.window = window
self.number = str(number)
def button_clicked(self):
self.window.ui.lb_result.setText(self.number)
然后在NumberButton
中實例化,例如:
...
self.button_0 = buttons.NumberButton(self, 0)
...
如果你只導入模塊 python 應該會自動避免循環導入。 import ui
和import buttons
也是如此
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.