如何在整个代码的__init__方法中使用定义的变量?

时间:2018-10-24 13:33:04

标签: python tkinter tkinter-menu

在这里,我正在尝试使用python和tkinter以及OOP构建文本编辑器。但是问题是我无法在代码中使用预定义的变量。

from tkinter import *
from tkinter import Tk, Menu, Label, PhotoImage, StringVar, IntVar
from PIL import Image, ImageTk

PROGRAM_NAME = 'PyEdit'


class TextEditor:

    def __init__(self, root):

        self.root = root
        self.root.tk.call('wm', 'iconphoto', self.root._w, photo)
        self.root.title(PROGRAM_NAME)
        self.root.geometry('350x280')
        self.init_gui()

        self.title_image = Image.open('Text-Edit-icon.png')
        self.photo = ImageTk.PhotoImage(title_image)
        self.help = Image.open('icons/helpicon.png')
        self.new_icon = PhotoImage(file='icons/new_file.gif')
        self.save_icon = PhotoImage(file='icons/save.gif')
        self.cut_icon = PhotoImage(file='icons/cut.gif')
        self.copy_icon = PhotoImage(file='icons/copy.gif')
        self.undo_icon = PhotoImage(file='icons/undo.gif')
        self.open_icon = PhotoImage(file='icons/open_file.gif')
        self.about_icon = PhotoImage(file='icons/about.gif')
        self.redo_icon = PhotoImage(file='icons/redo.gif')
        self.find_icon = PhotoImage(file='icons/onfind.gif')
        self.help_icon = ImageTk.PhotoImage(help)
        self.paste_icon = PhotoImage(file='icons/paste.gif')

    def create_menu_bar(self):
        menu_bar = Menu(self.root)
        edit_menu = Menu(menu_bar, tearoff=0)
        edit_menu.add_command(label='Undo', accelerator='Ctrl-Z', image=self.undo_icon)
        edit_menu.add_command(label='Redo', accelerator='Ctrl-Y', image=self.redo_icon)
        edit_menu.add_command(label='Cut', accelerator='Ctrl-X', image=self.cut_icon)
        edit_menu.add_command(label='Copy', accelerator='Ctrl-C', image=self.copy_icon)
        edit_menu.add_command(label='Paste', accelerator='Ctrl-V', image=self.paste_icon)
        edit_menu.add_separator()
        edit_menu.add_command(label='Select All', accelerator='Ctrl-A', )
        menu_bar.add_cascade(label='Edit', menu=edit_menu)
        self.root.config(menu=menu_bar)

    def init_gui(self):
        self.create_menu_bar()

if __name__ == "__main__":
    root = Tk()
    TextEditor(root)
    root.mainloop()

我得到的错误是

Traceback (most recent call last):
  File "SoundBoard.py", line 51, in <module>
     TextEditor(root)
  File "SoundBoard.py", line 15, in __init__
    self.init_gui()
  File "SoundBoard.py", line 47, in init_gui
    self.create_menu_bar()
  File "SoundBoard.py", line 36, in create_menu_bar
    edit_menu.add_command(label='Undo', accelerator='Ctrl-Z', image=self.undo_icon)
AttributeError: 'TextEditor' object has no attribute 'undo_icon'

我尝试将photoimage块放置在其他位置,这不起作用。我也在create_menu_bar中尝试过,但没有错误,但是也没有用。

1 个答案:

答案 0 :(得分:5)

我认为这仅仅是因为您已经在初始化变量之前放置了self.init_gui(),并将其放置在__init__方法的末尾,并且我猜它应该可以工作。