Tuesday, January 22, 2019

tkinter examples -1

We have learned about the basics of tkinter module in the previous posts so it's time to look at some examples to have a better understanding of tkinter module.

Let's make a program to calculate the square root of a given number. See the code below:

from tkinter import *
import math

def calculate():
   
    num = int(entry.get())
    squareroot = math.sqrt(num)
    output_label.configure(text = 'Square root: {:.1f}'.format(squareroot))
    entry.delete(0,END)
   
   
root = Tk()

message_label = Label(text = 'Enter a number',font =('Verdana',16))
output_label = Label(font=('Verdana', 16))
entry = Entry(font =('Verdana',16),width =4)
calc_button = Button(text='Ok', font = ('Verdana',16),command = calculate)

message_label.grid(row=0,column=0)
entry.grid(row=0,column=1)
calc_button.grid(row=0,column=2)
output_label.grid(row=1,column=0,columnspan=3)

mainloop()

The output of this program is shown below:



The program asks us to input a number whose square root is to be calculated. After entering the number we click Ok and the Square root value is displayed .

We know that a label is a place for our program to place some text on the screen. The following code creates a label and places it on the screen:

message_label = Label(text = 'Enter a number',font =('Verdana',16))
message_label.grid(row=0,column=0)

We call Label to create a new label. The capital L is required. Our label’s name is message_label. Once created, we use the grid method to place the label on the screen. There are a number of options we can change including font size and color. For example:

message_label = Label(text = 'Enter a number',font =('Verdana',16,'bold'),bg='gray',fg='black')

Here we have set the font style to bold and changed the background and foreground colors of the label. Now if we see the output it'll look as shown below:




 A few common options for the keyword arguments for Label() are:

• font — The basic structure is font= (font name, font size, style). We can leave out the font size or the style. The choices for style are 'bold', 'italic', 'underline', 'overstrike', 'roman', and 'normal' (which is the default). We can combine multiple styles like this: 'bold italic'.

• fg and bg — These stand for foreground and background. Many common color names can be used, like 'blue', 'green', etc.

• width—This is 'how many characters long the label should be'. If we leave this out, Tkinter will base the width off of the text we put in the label. This can make for unpredictable results, so it is good to decide ahead of time how long we want our label to be and set the width accordingly.

• height — This is 'how many rows high the label should be'. We can use this for multiline labels. Use newline characters in the text to get it to span multiple lines. For example, text='Okay\nSubmit'.

After we’ve created output_label , output_label = Label(font=('Verdana', 16)), we use its configure method to change the label properties as shoen below:

output_label.configure(text = 'Square root: {:.1f}'.format(squareroot))

Setting text to something using the configure method is kind of like the GUI equivalent of a print statement. However, in calls to configure we cannot use commas to separate multiple things to print. We instead need to use string formatting. Here is a print statement and its equivalent using the configure method.

print('Square root: ',squareroot)
output_label.configure(text = 'Square root: {:.1f}'.format(squareroot))

The configure method works with most of the other widgets.

We know that the grid method is used to place things on the screen. It lays out the screen as a rectangular grid of rows and columns. The first few rows and columns are shown below.

(row=0, column=0) (row=0, column=1) (row=0, column=2)
(row=1, column=0) (row=1, column=1) (row=1, column=2)
(row=2, column=0) (row=2, column=1) (row=2, column=2)

There are optional arguments, rowspan and columnspan, that allow a widget to take up more than one row or column. The following lines placed our labels on the screen:

message_label.grid(row=0,column=0)
entry.grid(row=0,column=1)
calc_button.grid(row=0,column=2)
output_label.grid(row=1,column=0,columnspan=3)

As seen in the figure below our message_label text is placed at  row=0,column=0, the entry text box at row=0,column=1, the Ok Button at row=0,column=2 and the most interesting is output_label text Square root: which uses a columnspan=3 value hence occupy more than one column space.



If we remove the columnspan=3 argument then the output will be :



The following lines creates a simple entry box and places it on the screen:

entry = Entry(font =('Verdana',16),width =4)
entry.grid(row=0,column=1)

The options that work with labels work with entry boxes (and most of the other widgets). The width option is particularly helpful because the entry box will often be wider than you need.To get the text from an entry box, use its get method. This will return a string. If we need numerical data, we use eval (or int or float) on the string. In our example we used int as shown below:

num = int(entry.get())

After the calculation is done the entry box is cleared using the delete() as shown below:

entry.delete(0,END)

Usually the entry box is blank, in case if we prefer to keep some default text in the entry box we can use the following code:

entry.insert(0,'type here')

The following lines creates a button and places it on the screen:

calc_button = Button(text='Ok', font = ('Verdana',16),command = calculate) 
calc_button.grid(row=0,column=2)

To get the button to do something when clicked, we use the command argument. It is set to the name
of a function, called a callback function. When the button is clicked, the callback function is called. When our program starts, the button label says Ok. When the button is clicked, the callback function
calculate is called which calculates the square root and prints the result.

Here I am ending today's topic, till we meet next keep practicing and learning Python as Python is easy to learn!










   
   


Share:

0 comments:

Post a Comment