我正在尝试在Python中创建GUI但由于某种原因它无法正常工作。 GUI应该有一个信息按钮和一个退出按钮。我知道这是一个简单的错误,我应该能够调试,但我无法找到它。
回溯错误消息:
在 区= GUI()
self.info_button = tkinter.Button(self.bottom_frame,text =" Show Info", command = self.showinfo)AttributeError:' GUI'对象没有属性 ' showinfo'
这是我的代码:
import tkinter
import tkinter.messagebox
class GUI:
def __init__(self):
#main window
self.main_window = tkinter.Tk()
#create two frames
self.top_frame= tkinter.Frame()
self.bottom_frame = tkinter.Frame()
#object of StringVar class
self.value = tkinter.StringVar()
#top frame label
self.info_label = tkinter.Label(self.top_frame,textvariable = self.value)
#information button that displays the information about the name and address
self.info_button = tkinter.Button(self.bottom_frame, text="Show Info", command=self.showinfo)
#quit button that closes the program
self.quit_button = tkinter.Button(self.bottom_frame, text ='Quit', command=self.main_window.destroy)
#pack method for packing widgets
self.info_label.pack()
self.info_button.pack(side='left')
self.quit_button.pack(side='left')
self.top_frame.pack()
self.bottom_frame.pack()
#main loop for running the program
tkinter.mainloop()
def showinfo(self):
inf = '\tSteven Marcus\n\t274 Baily Drive\n\tWaynesville, NC 27999'
self.value.set(inf)
#call the main function
gu=GUI()
答案 0 :(得分:1)
Python中的缩进非常重要,缩进是关闭的,您需要缩进整个def showinfo(self):
块,以便它位于GUI
类之下。
import tkinter
import tkinter.messagebox
class GUI:
def __init__(self):
#main window
self.main_window = tkinter.Tk()
#create two frames
self.top_frame= tkinter.Frame()
self.bottom_frame = tkinter.Frame()
#object of StringVar class
self.value = tkinter.StringVar()
#top frame label
self.info_label = tkinter.Label(self.top_frame,textvariable = self.value)
#information button that displays the information about the name and address
self.info_button = tkinter.Button(self.bottom_frame, text="Show Info", command=self.showinfo)
#quit button that closes the program
self.quit_button = tkinter.Button(self.bottom_frame, text ='Quit', command=self.main_window.destroy)
#pack method for packing widgets
self.info_label.pack()
self.info_button.pack(side='left')
self.quit_button.pack(side='left')
self.top_frame.pack()
self.bottom_frame.pack()
#main loop for running the program
tkinter.mainloop()
def showinfo(self): # indent these:
inf = '\tSteven Marcus\n\t274 Baily Drive\n\tWaynesville, NC 27999'
self.value.set(inf)
#call the main function
gu=GUI()