简体   繁体   中英

Can i access a variable created in a main() function, in a separate class

Not quite sure how to word this, think i may be being stupid but i am declaring the variable albumInfoArray in my main() function. Is there a way to access this from my mainscreen class. For example the skip_button_clicked() method needs to access the value in the albumInfoArray and it seems this array isnt in its scope.

class MainScreen:
    def __init__(self):
        self.main_screen = Tk()
        self.main_screen.geometry ('500x600+100+100')
        self.main_screen.title("Album")
        self.main_screen.configure(background = 'aliceblue')
        self.albumTemp = Image.open("/Users/peacockben/Documents/Ben/Album Guesser/CurrentImage.jpeg")
        self.albumTemp = self.albumTemp.resize((250,250), Image.ANTIALIAS)
        self.album = ImageTk.PhotoImage(self.albumTemp)
        self.create_widgets()

    def create_widgets(self):
        self.pad1 = Label(self.main_screen, text = " ", bg = "blue", height = 2,width = 13)
        self.pad1.grid(row = 0, column = 0)
        self.Title = Label(self.main_screen, text = "Albumle",bg ="blue", font = ('',36, 'bold'))
        self.Title.grid(row = 1, column = 1)
        self.AlbumImg = Label(self.main_screen, image = self.album, bg = 'aliceblue')
        self.AlbumImg.grid(row = 2, column = 1)
        self.skip_button = Button(self.main_screen,text = "Skip", height = "2",width = "15")
        self.skip_button.grid(row = 3, column = 1)

    def skip_button_clicked(self):
        print(albumInfoArray)


def main():
    albumInfoArray = get_album_info(get_album_index())
    blur_image(albumInfoArray[2],50)
    program = MainScreen()
    program.main_screen.mainloop()

albumInfoArray is in the scope of the main function and shouldn't be accesible outside it.

You could try by declaring it as global:

def main():
    global albumInfoArray
    albumInfoArray = get_album_info(get_album_index())
    etc...

A variable if declared inside the main() is accessible only in the main. You cannot even access it within the same class where main() is. You can try declaring the variable as a global variable in the same class as main is.`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM