簡體   English   中英

僅當模塊存在時,如何從模塊導入 class 的實例

[英]How to import an instance of a class from a module only if it exists

我正在做的項目是塔防級別編輯器。 我認為對於這個問題,了解結構很重要。所以基本上,我們可以有很多項目,每個項目可以容納很多塔。 我正在制作 GUI,特別是滑塊。 我想加載用戶上次退出程序時滑塊所持有的值。 為此,這些值存儲在文本文件中。 為了裝載塔,我有一個 class。

class Workspace:
    def __init__(self):
        t = file.loadtowers(project.getprojectname())
        for tower in t:
            if tower.name == project.tower:
                self.speedslider = Slider([990, 10], text="Attack Speed/ s", start=int(tower.attackspeed), factor=40)
                self.damageslider = Slider([990, 50], text="Attack Damage", start=int(tower.damage))
                self.radiusslider = Slider([990, 90], text="Range Radius", start=int(tower.radius))
                self.levelslider = Slider([990, 130], text="Max Level", start=int(tower.max), factor=5)
                step = literal_eval(tower.step)
                self.step = [TickBox(text="Damage", value=step[0]), TickBox(text="Range", value=step[1])
                             , TickBox(text="Attack speed", value=step[2])]
                stepupby = literal_eval(tower.stepupby)
                self.damagestep = Slider([990, 340], text="Attack Damage", start=int(stepupby[0]))
                self.radiusstep = Slider([990, 380], text="Range Radius", start=int(stepupby[1]))
                self.attackspeed = Slider([990, 420], text="Attack Speed", start=int(stepupby[2]))
                self.chooseimage = RectButton(text="Choose Image", border=True)
                self.savebutton = RectButton(text="Save", border=True)

我想在實例化 class 時加載值,因為我只想加載一次值,然后讓用戶更改它們。 但是,我的問題是我只能在用戶選擇塔后實例化 class,因為我需要知道用戶想要在哪個塔上工作。

def openproject(self):
        for b in self.buttons:
            if b.clicked():
                project.settower(b.text)
                global towerworkspace
                towerworkspace = Workspace()
                state.active = "tower workspace"

但是現在,我在main.py中遇到了一個導入錯誤,因為只有在towerworkspace運行時才定義了openproject 那么我將如何解決這個問題呢? 使用 function 會使一切變得更簡單,但我想不出一種只加載一次值的方法,因為 function 必須處於循環中。 只有在創建之后導入towerworkspace理想的,但我不知道該怎么做。 感謝您的幫助

main.py

import pygame
import sys
from time import time
from home import home
from createproject import createproject, existingprojects
from towerworkspace import towerhome, towerworkspace

from GUI import popup
from States import state


class Editor:
    def __init__(self, winWidth, winHeight):
        self.win = pygame.display 

        self.display = self.win.set_mode((winWidth, winHeight)) #Initialize the pygame window with given size
        self.win.set_caption("A Level computer science project - Level Editor") #Set title for the window


editor = Editor(1200, 600)# Instantiation of Editor class with values 1200, 600 which is used as the screen size

# This function accepts event queue from the operating system as an argument and if one of those events is pygame.QUIT it exits the program.
def handleExit(events):
    for e in events:
        if e.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

def render():
    editor.display.fill((100, 100, 100)) # Fills the window with a grey-ish color every frame, which is the background
    if state.active == "create project":
        createproject.render(editor.display)
        existingprojects.render(editor.display)
    if state.active == "home":
        home.render(editor.display)
    if state.active == "tower home":
        towerhome.render(editor.display)
    if state.active == "tower workspace":
        towerworkspace.render(editor.display)

    popup.popup(editor.display)
    

def logic(events, window):        
    if state.active == "create project":
        createproject.logic(events, window)
        createproject.feedevents(events)
        existingprojects.logic(events)
        existingprojects.refresh()
    if state.active == "home":
        home.logic()
    if state.active == "tower home":
        towerhome.feedevents(events)
        towerhome.logic(events)
        towerhome.openproject()
        towerhome.refresh()
    if state.active == "tower workspace":
        towerworkspace.feedevents(events)
        towerworkspace.updatevalues(events)
    popup.handleactive()
 

# The application loop
while True:
    events = pygame.event.get() #  Request event queue from the operating system
    popup.handleactive()
    handleExit(events)
    render()
    logic(events, editor.display)
    editor.win.flip()

錯誤:

 ImportError: cannot import name 'towerworkspace' from 'towerworkspace' 

從頂部的導入中刪除 towerworkspace 並在用戶單擊后使用它,如下所示:

    if state.active == "tower workspace":
        from towerworkspace import towerworkspace
        towerworkspace.feedevents(events)
        towerworkspace.updatevalues(events)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM