Create a new tkinter widget: Inputbox

Tkinter should have a widget to get an input from a popup window? Why we cannot create our own widget for that?

import tkinter as tk 

class Inputbox():
    def __init__(self, text=""):
        self.root = tk.Tk()
        self.get = ""
        self.root.geometry("300x100")
        self.root.title("Inputbox")
        self.label_file_name = tk.Label(self.root, text=text)
        self.label_file_name.pack()
        self.entry = tk.Entry(self.root)
        self.entry.pack()
        self.entry.focus()
        self.entry.bind("<Return>", lambda x: self.getinput(self.entry.get()))
        self.root.mainloop()

    def getinput(self, value):
        self.get = value
        self.root.destroy()


inp = Inputbox(text="What is your favourite site?")
print(inp.get)

This is the output:

This will return the string “pythonprogramming”

Using ttk for a prettier inputbox

I want to give you an example about how complicated can be ttk sometimes. It has a more modern style, but to change the color and the background can be very difficult. Take a look at this code to see what I mean:

import tkinter as tk
import tkinter.ttk as ttk
class Inputbox:
	def __init__(self, text=""):
		"""An inputbox made by you
		example:
		inp = Inputbox(text="What is you favourite site?")
		print(inp.get)
		"""
		self.root = tk.Tk()
		self.get = ""
		self.root.title("Inputbox")
		self.root["bg"] = "cyan"
		style = ttk.Style()
		style2 = ttk.Style()
		style.configure("BW.TLabel", foreground="red", background="yellow")
#		style2.configure("EntryStyle.TEntry",
#							foreground="blue",
#							background=[("active","red")],
#							fieldbackground="red")

		estyle = ttk.Style()
		estyle.element_create("plain.field", "from", "clam")
		estyle.layout("EntryStyle.TEntry",
	                   [('Entry.plain.field',
	                   	{'children':
	                   			[('Entry.background', {'children':
	                   				[('Entry.padding', {'children':
	                   					[('Entry.textarea', {'sticky': 'nswe'})],
	                      		'sticky': 'nswe'})],
	                      		'sticky': 'nswe'})],
	                      'border':'2',
	                      'sticky': 'nswe'})])
		estyle.configure("EntryStyle.TEntry",
	                 background="green", 
	                 foreground="blue",
	                 fieldbackground="gold")
		self.label = ttk.Label(self.root, text = text, font="Arial 20", style="BW.TLabel")

		self.label.pack(fill=tk.BOTH, expand=1)

		self.entry = ttk.Entry(self.root, font="Arial 20", style="EntryStyle.TEntry")

		self.entry.pack(fill=tk.BOTH, padx=10, pady=10)
		self.entry.focus()
		self.entry.bind("<Return>", lambda x: self.getinput())
		self.root.mainloop()

	def getinput(self):
		self.get = self.entry.get()
		self.root.destroy()


inp = Inputbox(text="What is you favourite site?")
print(inp.get)

Tkinter test for students

Tkinter articles