在这里,我正在尝试使用 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
没有错误,但它也不起作用。