Google News
logo
Tkinter Interview Questions
The tkinter package (“Tk interface”) is the standard Python interface to the Tcl/Tk GUI toolkit. Both Tk and tkinter are available on most Unix platforms, including macOS, as well as on Windows systems.

Tkinter supports a range of Tcl/Tk versions, built either with or without thread support. The official Python binary release bundles Tcl/Tk 8.6 threaded. See the source code for the _tkinter module for more information about supported versions.
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task.
 
To create a tkinter app :
 
1. Importing the module – tkinter
2. Create the main window (container)
3. Add any number of widgets to the main window
4. Apply the event Trigger on the widgets.
 
 
Importing tkinter is same as importing any other module in the Python code. Note that the name of the module in Python 2.x is ‘Tkinter’ and in Python 3.x it is ‘tkinter’.
App and Root are two different objects. root is the root window into which all other widgets go. It is an instance of the class Tk, and every tkinter application must have exactly one instance of this class. app is an instance of the class App, which is a subclass of Frame. A frame is typically used as a container for other widgets, in this case the widgets that make up the app (except for the root window). This frame is packed inside the root window. app and root are two completely different things. root is a container for app.
The pack() widget is used to organize widget in the block. The positions widgets added to the python application using the pack() method can be controlled by using the various options specified in the method call.
 
However, the controls are less and widgets are generally added in the less organized manner.
 
Syntax : widget.pack(options)
The grid() geometry manager organizes the widgets in the tabular form. We can specify the rows and columns as the options in the method call. We can also specify the column span (width) or rowspan(height) of a widget.
 
This is a more organized way to place the widgets to the python application. The syntax to use the grid() is given below.
 
Syntax : widget.grid(options)
The place() geometry manager organizes the widgets to the specific x and y coordinates.
 
Syntax : widget.place(options) 
expand : When set to true, widget expands to fill any space not otherwise used in widget's parent.
 
fill : Determines whether widget fills any extra space allocated to it by the packer, or keeps its own minimal dimensions: NONE (default), X (fill only horizontally), Y (fill only vertically), or BOTH (fill both horizontally and vertically).
 
side : Determines which side of the parent widget packs against: TOP (default), BOTTOM, LEFT, or RIGHT.
Column : The column number in which the widget is to be placed. The leftmost column is represented by 0.
 
Columnspan : The width of the widget. It represents the number of columns up to which, the column is expanded.
 
ipadx, ipady : It represents the number of pixels to pad the widget inside the widget's border.
 
padx, pady : It represents the number of pixels to pad the widget outside the widget's border.
 
row : The row number in which the widget is to be placed. The topmost row is represented by 0.
 
rowspan : The height of the widget, i.e. the number of the row up to which the widget is expanded.
 
Sticky : If the cell is larger than a widget, then sticky is used to specify the position of the widget inside the cell. It may be the concatenation of the sticky letters representing the position of the widget. It may be N, E, W, S, NE, NW, NS, EW, ES.
 
 
Anchor : It represents the exact position of the widget within the container. The default value (direction) is NW (the upper left corner)
 
bordermode : The default value of the border type is INSIDE that refers to ignore the parent's inside the border. The other option is OUTSIDE.
 
height, width : It refers to the height and width in pixels.
 
relheight, relwidth : It is represented as the float between 0.0 and 1.0 indicating the fraction of the parent's height and width.
 
relx, rely : It is represented as the float between 0.0 and 1.0 that is the offset in the horizontal and vertical direction.
 
x, y : It refers to the horizontal and vertical offset in the pixels.
The Text widget accepts multiline user input, where you can type text and perform operations like copying, pasting, and deleting. There are certain ways to disable the shortcuts for various operations on a Text widget.
 
In order to disable copy, paste and backspace in a Text widget, you’ve to bind the event with an event handler and return break using lambda keyword in python.
APIs are extremely useful in implementing a service or feature in an application. APIs help to establish the connection between the server and a client, so whenever a client sends a request using one of the API methods to the server, the server responds with a status code (201 as a successful response) to the client.
 
You can make a request to any API you want using one of the methods (GET, POST, PUT or DELETE). However, if you want to create an application where you need a request to the server using one of the publicly available API (for example, Cat Facts API), then you can use the requests module in the Python library.
 
In the following application, we will create a textbox which will display the response (text) retrieved from the server using one of the Cat Facts API. You will also need to make sure that you have already installed the requests module in your environment. To install requests module, you can use the following command,
 
pip install requests
If you want to create a dropdown list of items and enable the items of list to be selected by the user, then you can use the Combobox widget. The Combobox widget allows you to create a dropdown list in which the list of items can be selected instantly. However, if you want to get the index of selected items in the combobox widget, then you can use the get() method. The get() method returns an integer of the selected item known as the index of the item.
 
Example : Let’s take an example to see how it works. In this example, we have created a list of days of weeks in a dropdown list and whenever the user selects a day from the dropdown list, it will print and display the index of selected item on a Label widget. To print the index, we can concatenate the string by typecasting the given index into string.
There are various methods and built-in functions available with the messagebox library in tkinter. Let's assume you want to display a messagebox and take some input from the user in an Entry widget. In this case, you can use the askstring library from simpledialog. The askstring library creates a window that takes two arguments, the title of the window, and the input title before the Entry widget.
A StringVar object in Tkinter can help manage the value of a widget such as an Entry widget or a Label widget. You can assign a StringVar object to the textvariable of a widget.

For example :
data = ['Car', 'Bus', 'Truck', 'Bike', 'Airplane']
var = StringVar(win)
my_spinbox = Spinbox(win, values=data, textvariable=var)
Here, we created a list of strings followed by a StringVar object "var". Next, we assigned var to the textvariable of a Spinbox widget. To get the current value of the Spinbox, you can use var.get().
To display the current date in tkinter window, we will use the datetime library.
 
date = dt.datetime.now()

Steps : 

* Import the required libraries and create an instance of tkinter frame.
* Set the size of the frame using geometry method.
* Call datetime.now() and store the value in a variable "date".
*  Next, create a label to display the date. In the text parameter of the label, pass the date value and format the data as text=f"{date:%A, %B %d, %Y}".
   * %A – Day of the week, full name
   * %B – Full month name
   * %d – Day of the month
   * %Y – Year with century as a decimal number
* Finally, run the mainloop of the application window.
There are two different ways in which we can get an automatically maximized window in Tkinter.
 
* We can use the state() method of Tkinter and invoke it with the attribute "zoomed".
      root.state("zoomed")
* The second approach is to use the attributes method of Tkinter with the parameter "-fullscreen" and set it to True.

By default, Tkinter creates a window of a predefined size. The dimensions of the window can be customized using the geometry method. For example,
     root.geometry("700 x 350")
Using the Canvas widget, we can create text, images, graphics, and visual content to add to the Canvas widget. If you need to configure the Canvas item dynamically, then tkinter provides itemconfig(**options) method. You can use this method to configure the properties and attributes of the Canvas items. For example, if we create a line inside the Canvas widget, we can configure its color or width using itemconfig() method.
The Tkinter library has many built-in functions and methods which can be used to implement the functional part of an application. We can use messagebox module in Tkinter to create various popup dialog boxes. The messagebox property has different types of built-in popup windows that the users can use in their applications.
 
If you need to display the error messagebox in your application, you can use showerror("Title", "Error Message") method. This method can be invoked with the messagebox itself.
To make a new folder using askdirectory dialog in Tkinter, we can take the following steps :
 
  * Import the required modules. filedialog module is required for askdirectory method. os module is required for makedirs method.
  * Create an instance of tkinter frame.
  * Set the size of the frame using win.geometry method.
  * Define a user-defined method "create_subfolder". Inside the method, call filedialog.askdirectory to select a folder and save the path in a variable, source_path.
  * We can use askdirectory method of filedialog to open a directory. Save the path of the selected directory in a 'path' variable.
  * Then, use os.path.join and makedirs to create a sub-folder inside the parent directory.
  * Create a button to call the create_subfolder method.
The Pillow library in Python contains all the basic image processing functionality. It is an open-source library available in Python that adds support to load, process, and manipulate the images of different formats.
 
Let's take a simple example and see how to embed an Image in a Tkinter canvas using Pillow package (PIL). Follow the steps given below.
 
Steps : 
* Import the required libraries and create an instance of tkinter frame.
from tkinter import *
from PIL import Image, ImageTk
* Set the size of the frame using root.geometry method.
* Next, create a Canvas widget using canvas() function and set its height and width.
* Open an image using Image.open() and then convert it to an PIL image using ImageTk.PhotoImage(). Save the PIL image in a variable "img".
* Next, add the PIL image to the Canvas using canvas.create_image().
* Finally, run the mainloop of the application window.