-1

This is the code:

from tkinter import *
import os

class App:

    charprefix = "character_"
    charsuffix = ".iacharacter"
    chardir = "data/characters/"
    charbioprefix = "character_biography_"

    def __init__(self, master):
        self.master = master
        frame = Frame(master)
        frame.pack()

        # character box
        Label(frame, text = "Characters Editor").grid(row = 0, column = 0, rowspan = 1, columnspan = 2)
        self.charbox = Listbox(frame)
        for chars in []:
            self.charbox.insert(END, chars)
        self.charbox.grid(row = 1, column = 0, rowspan = 5)
        charadd = Button(frame, text = "   Add   ", command = self.addchar).grid(row = 1, column = 1)
        charremove = Button(frame, text = "Remove", command = self.removechar).grid(row = 2, column = 1)
        charedit = Button(frame, text = "    Edit    ", command = self.editchar).grid(row = 3, column = 1)

        for index in self.charbox.curselection():
            charfilelocale = self.charbox.get(int(index))
            charfile = open(app.chardir + app.charprefix + charfilelocale, 'r+')
            charinfo = self.charfile.read().splitlines(0)

Now what I want to know is, if I'm going to call charinfo in another function, what should I call it? I'm using Python 3.3 and app.charinfo or self.charinfo don't work. If my code is incorrect, can you help please correct it too? Thanks in advance.

falsetru
  • 357,413
  • 63
  • 732
  • 636
  • You cant call it, it is local variable of a function its scope is inside that function. if you want to use it in another class declare it as a class variable means instaed of charinfo type self.charinfo – duck Aug 14 '13 at 06:26

1 Answers1

0

Your current implementation declares it as a local variable, and hence in accessible outside. For that to work, the assignment needs to happen onto self.charinfo:

When you want to access charinfo from other places
- self.charinfo works from within the class definition, and
- app.charinfo works outside class / from the instance

for index in self.charbox.curselection():
    charfilelocale = self.charbox.get(int(index))
    charfile = open(app.chardir + app.charprefix + charfilelocale, 'r+')
    # notice the self.charinfo here
    self.charinfo = self.charfile.read().splitlines(0)

Its better to ensure the attribute self.charinfo is available outside the loop to avoid errors in case it loops 0 times

self.charinfo = None
for index in self.charbox.curselection():
    charfilelocale = self.charbox.get(int(index))
    charfile = open(app.chardir + app.charprefix + charfilelocale, 'r+')
    self.charinfo = self.charfile.read().splitlines(0)
Kalyan02
  • 1,416
  • 11
  • 16