2014-05-10 142 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()