【问题标题】:Python widgets and buttonPython 小部件和按钮
【发布时间】:2014-05-11 04:32:28
【问题描述】:

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

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

【问题讨论】:

    标签: python tkinter widget


    【解决方案1】:

    您需要使用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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-18
      • 1970-01-01
      • 2016-03-24
      • 1970-01-01
      • 1970-01-01
      • 2019-01-04
      • 2021-06-08
      • 1970-01-01
      相关资源
      最近更新 更多