tkinter退出崩溃

问题描述:

我对Tkinter很新。我在Tkinter制作了这个“Hello World”式的GUI程序。但是,每次单击退出按钮时,程序都会崩溃。提前致谢!tkinter退出崩溃

from Tkinter import * 
import sys 
class Application(Frame): 

def __init__(self,master=None): 

    Frame.__init__(self,master=None) 
    self.grid() 
    self.createWidgets() 

def createWidgets(self): 
    self.quitButton = Button(text='Quit',command=self.quit)#Problem here 
    self.quitButton.grid() 
app = Application() 
app.master.title("Sample application") 
app.mainloop() 
+0

您的缩进不正确。请花时间发布准确的代码样本。 – 2013-03-10 15:06:59

在Tkinter中,根元素是一个Tk对象。 Application应该是Tk一个子类,而不是Frame

from Tkinter import * 
import sys 

class Application(Tk): 
    def __init__(self): 
     Tk.__init__(self) 
     self.grid() 
     self.createWidgets() 
    def createWidgets(self): 
     self.quitButton = Button(text='Quit',command=self.destroy) # Use destroy instead of quit 
     self.quitButton.grid() 

app = Application() 
app.title("Sample application") 
app.mainloop() 

此代码工作现在罚款:

import tkinter 

class MyApp(tkinter.LabelFrame): 
    def __init__(self, master=None): 
     super().__init__(master, text="Hallo") 
     self.pack(expand=1, fill="both") 
     self.createWidgets() 
     self.createBindings() 
    def createWidgets(self): 
     self.label = tkinter.Label(self) 
     self.label.pack() 
     self.label["text"] = "Bitte sende ein Event" 
     self.entry = tkinter.Entry(self) 
     self.entry.pack() 
     self.ok = tkinter.Button(self) 
     self.ok.pack() 
     self.ok["text"] = "Beenden" 
     self.ok["command"] = self.master.destroy 
    def createBindings(self): 
     self.entry.bind("Entenhausen", self.eventEntenhausen) 
     self.entry.bind("<ButtonPress-1>", self.eventMouseClick) 
     self.entry.bind("<MouseWheel>", self.eventMouseWheel) 
    def eventEntenhausen(self, event): 
     self.label["text"] = "Sie kennen das geheime Passwort!" 
    def eventMouseClick(self, event): 
     self.label["text"] = "Mausklick an Position " \ 
     "({},{})".format(event.x, event.y) 
    def eventMouseWheel(self, event): 
     if event.delta < 0: 
      self.label["text"] = "Bitte bewegen Sie das Mausrad"\ 
      " in die richtige Richtung." 
     else: 
      self.label["text"] = "Vielen Dank!" 

root = tkinter.Tk() 
app = MyApp(root) 
app.mainloop() 

当您使用self.quit() Python解释器关机,而不关闭Tkinter的应用bieng。因此请尝试.destroy()命令,并在.mainloop()后使用sys.quit()。希望这可以帮助。

您使用__init__很困难。这样做:

from tkinter import * 
root = Tk() 

btn_quit = Button(root, text='Quit', command=quit()).pack() 
root.mainloop() 

如果你这样做self.quit,那就是quit命令这样的东西会崩溃! 希望这有助于!