Archive for the ‘Python’ Category.

How To Change The Label Font in TKinter

The font attribute of the label widget can be used to change the font style and size.

First, we will create a window with a label using the default font and size.

import tkinter as tk

win = tk.Tk()
win.geometry("750x450")

title_label = tk.Label(win, text="hello")
title_label.pack(pady=10)

win.mainloop()

Below is the window with the label’s default font and style.

Next, we will add the font attribute to the label widget to customize the font style and size. In this example, we are going to change the font style to “Impact” and the font size to 20. The possible font styles are listed on the page https://learn.microsoft.com/en-us/typography/font-list/.

import tkinter as tk

win = tk.Tk()
win.geometry("750x450")

title_label = tk.Label(win, text="hello", font= 'Impact 17')
title_label.pack(pady=10)


win.mainloop()

Below is the output with the label’s customized font style and size.

Displaying An Image With Python Tkinter

The aim of the tutorial is to display an image using Tkinter. The image will change when a button is pressed.

Step 1

Create the Tkinter window.

import tkinter as tk

win = tk.Tk()
win.geometry("750x450")

win.mainloop()

When executed the code should generate a window 750 by 450.

TK window

Step 2

Display the image in the window. The code will load the image into a variable called photo. The code then adds a Label to the window of the type image and populates the label with the photo. In this example, the image is called car-jump.gif and the python code will assume the image file is in the same directory as the python code.

import tkinter as tk

win = tk.Tk()
win.geometry("750x450")

photo = tk.PhotoImage(file='car-jump.gif')
image = tk.Label(win, image=photo)
image.pack()

win.mainloop()

When executed the code will create a window with an image.

Step 4

Add a button to the window. First, we are going to add a button to the window and confirm the button will print a message when clicked. In the next step, we will link the button to the image.

import tkinter as tk


def change_image():
    print("Button has been clicked")


win = tk.Tk()
win.geometry("750x450")

photo = tk.PhotoImage(file='car-jump.gif')
image = tk.Label(win, image=photo)
image.pack()

button = tk.Button(win, text="Click to change image", command=change_image)
button.pack()

win.mainloop()

When executed the window should show the image and a button.

Tk window with image and button

In the console window, you should see the message “Button has been clicked”, every time the button has been clicked.

Step 5

In this step we will add the code to the change_image function that will change the image from car to a flower. In this example, the code assumes the flower.gif file will be in the same folder as the python code.

import tkinter as tk


def change_image():
    global show_car, image
    filename = 'not set'
    if show_car:
        filename = 'car-jump.gif'
        show_car = False
    else:
        filename = 'flower.gif'
        show_car = True
    print("Setting image to " + filename)
    photo2 = tk.PhotoImage(file=filename)
    image.configure(image=photo2)
    image.image = photo2


win = tk.Tk()
win.geometry("750x450")

photo = tk.PhotoImage(file='car-jump.gif')
image = tk.Label(win, image=photo)
image.pack()

button = tk.Button(win, text="Click to change image", command=change_image)
button.pack()

show_car = False
win.mainloop()

When executed the code will show the car image.

When the button is clicked the image will change to a flower.

Generate safe filenames using Python

This function removes illegal  characters to create file names that are safe to use on most operating systems.

import string

## Make a file name that only contains safe charaters
# @param inputFilename A filename containing illegal characters
# @return A filename containing only safe characters
def makeSafeFilename(inputFilename):   
  try:
     safechars = string.letters + string.digits + " -_."
    return filter(lambda c: c in safechars, inputFilename)
   except:
     return ""  
  pass

print makeSafeFilename("test1******.txt")  # test1.txt

print makeSafeFilename("test2:\.txt") # test2.txt

print makeSafeFilename("test39328764876!%^&*().txt") # test39328764876.txt

Convert time in seconds to HH:MM:SS

## Convert time in seconds to hours:minutes:seconds
# @param sec Time in seconds
# @return The time in hh:mm:ss format
def SecToTime(Sec): 
  H = int(Sec / 3600)
  M = int(Sec / 60 - H * 60)
  S = int(Sec - (H * 3600 + M * 60))

  if len(str(H)) == 1: time = "0" + str(H) + ":"
  else: time = str(H) + ":"
 
  if len(str(M)) == 1: time = time + "0" + str(M) + ":"
  else: time = time + str(M) + ":"

  if len(str(S)) == 1: time = time + "0" + str(S) 
  else: time = time + str(S) 
  
  return time
  pass