import tkinter as tk
from tkinter import simpledialog
my_w = tk.Tk()
my_w.geometry("410x360")
my_w.title("www.plus2net.com") # Adding a title
my_i = simpledialog.askinteger("Input","Input an Integer",parent=my_w)
print(my_i)
my_w.mainloop()
We can collect float value like this. Here even we enter integer also we will get float data type. Try by entering string. Change the highlighted code above
my_f = simpledialog.askfloat("Input", "Input the price",parent=my_w)
If we are using simpledialog.askinteger() then any float or string input will show error message. Similarly for simpledialog.askfloat() we can enter integer ( it will be converted to float data type) but we can’t enter any string.
For simpledialog.askstring() we can enter integer or float data types but it will store them as string.
Here is an example of message we will get if we enter string while using simpledialog.askintger()
If user clicks the Cancel button then the value stored in the variable my_s will be None. Here we will add one if condition check before using the same.
my_s = simpledialog.askstring("Input", "Input your Name",parent=my_w)
if my_s: # user has not cancelled the input.
l1=tk.Label(my_w,font=font1,text="welcome "+my_s)
l1.grid(row=0,column=0,padx=10,pady=20)
print(my_s)
In above codes the dialog box opens directly along with the parent window. Now we will try to open the dialog box when the entry widget is in focus.
On Submit of the dialog box , the data as entered by user will be displayed inside the Entry box.
Here we bind the FocusIn event of the entry box.
e1.bind("<FocusIn>", my_entry)
The function my_entry() triggers on focus and opens the Simpledialog box to take user input. The user input is collected using the my_str the StringVar which is connected to Entry widget.
import tkinter as tk
from tkinter import simpledialog
my_w = tk.Tk()
my_w.geometry("410x160")
my_w.title("www.plus2net.com") # Adding a title
font1=('Times',30,'normal')
def my_entry(*args):
my_str.set(simpledialog.askstring("Input", "Input your Name",parent=my_w))
my_str=tk.StringVar()
e1=tk.Entry(my_w,font=font1,textvariable=my_str,width=15)
e1.grid(row=0,column=0,padx=10,pady=20)
e1.bind("<FocusIn>", my_entry)
my_w.mainloop()