Creating a popup message box with an Entry field

前端 未结 3 2178
情深已故
情深已故 2020-12-09 12:05

I want to create a popup message box which prompts user to enter an input. I have this method inside a class. I am basing my code on this guide by java2s.

cl         


        
相关标签:
3条回答
  • 2020-12-09 12:31

    I just tried this:

    def get_me(): s = simpledialog.askstring("input string", "please input your added text")

    Source: https://www.youtube.com/watch?v=43vzP1FyAF8

    0 讨论(0)
  • 2020-12-09 12:33

    I'm a little confused about your two different blocks of code. Just addressing the first block of code, nothing happens because you never enter the mainloop. To do that, you need to call root.mainloop(). The typical way of doing this is to add a button to root widget and bind a callback function to the Button (which includes d=MyDialog() and root.wait_window(d.top))

    Here's some basic code which I hope does what you want ...

    from Tkinter import *
    import sys
    
    class popupWindow(object):
        def __init__(self,master):
            top=self.top=Toplevel(master)
            self.l=Label(top,text="Hello World")
            self.l.pack()
            self.e=Entry(top)
            self.e.pack()
            self.b=Button(top,text='Ok',command=self.cleanup)
            self.b.pack()
        def cleanup(self):
            self.value=self.e.get()
            self.top.destroy()
    
    class mainWindow(object):
        def __init__(self,master):
            self.master=master
            self.b=Button(master,text="click me!",command=self.popup)
            self.b.pack()
            self.b2=Button(master,text="print value",command=lambda: sys.stdout.write(self.entryValue()+'\n'))
            self.b2.pack()
    
        def popup(self):
            self.w=popupWindow(self.master)
            self.b["state"] = "disabled" 
            self.master.wait_window(self.w.top)
            self.b["state"] = "normal"
    
        def entryValue(self):
            return self.w.value
    
    
    if __name__ == "__main__":
        root=Tk()
        m=mainWindow(root)
        root.mainloop()
    

    I get the value from the popupWindow and use it in the main program (take a look at the lambda function associated with b2).

    Main window:

    "Click me" window:

    Main window while "click me" is open:

    0 讨论(0)
  • 2020-12-09 12:35
    import tkinter as tk
    from tkinter import simpledialog
    
    ROOT = tk.Tk()
    
    ROOT.withdraw()
    # the input dialog
    USER_INP = simpledialog.askstring(title="Test",
                                      prompt="What's your Name?:")
    
    # check it out
    print("Hello", USER_INP)
    

    Enjoy ...

    0 讨论(0)
提交回复
热议问题