2013-03-10 176 views
2

我對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

回答

4

在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() 
0

此代碼工作現在罰款:

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() 
0

當您使用self.quit() Python解釋器關機,而不關閉Tkinter的應用bieng。因此請嘗試.destroy()命令,並在.mainloop()後使用sys.quit()。希望這可以幫助。

1

您使用__init__很困難。這樣做:

from tkinter import * 
root = Tk() 

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

如果你這樣做self.quit,那就是quit命令這樣的東西會崩潰! 希望這有助於!