2014-05-10 95 views
0

我试图向我的程序中添加一个“完成”按钮,该按钮将打印两个输入小部件的内容到一个新框中。我可以让按钮出现,但我无法将信息显示在新框中。我究竟做错了什么?Python小部件和按钮

from Tkinter import * 

class Application(Frame): 
    def __init__(self, master=None): 
     Frame.__init__(self, master) 
     self.grid() 
     self._name = StringVar() 
     self._name.set("Enter name here") 
     self._age = IntVar() 
     self._age.set("Enter age here") 
     top = self.winfo_toplevel()   # find top-level window 
     top.title("Entry Example") 

     self._createWidgets() 

     self._button = Button(self, 
          text = "Done") 
     self._button.grid(row = 1, column = 0, columnspan = 2) 

    def _createWidgets(self): 
     textEntry = Entry(self, takefocus=1, 
          textvariable = self._name, width = 40) 
     textEntry.grid(row=0, sticky=E+W) 

     ageEntry = Entry(self, takefocus=1, 
         textvariable = self._age, width = 20) 
     ageEntry.grid(row=1, sticky=W) 

    def _widget(self): 
     tkMessageBox.showinfo 



# end class Application 

def main(): 
Application().mainloop() 

回答

0

您需要使用command:选项为按钮指定一个操作。

要得到什么写在Entry您需要使用get()方法。

showinfo您需要两个参数,一个是标题,另一个是将要显示的内容。

您还需要import tkMessageBox

这是一个工作示例。

import Tkinter as tk 
import tkMessageBox 

class Example(tk.Frame): 
    def __init__(self,root): 
     tk.Frame.__init__(self, root) 

     self.txt = tk.Entry(root) 
     self.age = tk.Entry(root) 
     self.btn = tk.Button(root, text="Done", command=self.message) 

     self.txt.pack() 
     self.age.pack() 
     self.btn.pack() 

    def message(self): 
     ent1 = self.txt.get() 
     ent2 = self.age.get() 
     tkMessageBox.showinfo("Title","Name: %s \nAge: %s" %(ent1,ent2)) 



if __name__=="__main__": 
    root = tk.Tk() 
    root.title("Example") 
    example = Example(root) 
    example.mainloop()