Add a label to the window
One of the most used widget is probably the label. It’s dondamental for a GUI to put text on it so that the user knows what some other widgets are for or how to use them. You can also have interaction with labels, you can click on them, and they can change the text when something happens.
To add a label to the window we can add this lines of code to our program
label = tk.Label(root, text="This is a label") label['bg'] = 'yellow' # this is the backfround color label.pack()
We attach the label to the root, that is the window name, and then we change the text attribute to make the text appear on the label. To change the background color we make the same thing that we made for the root. To make the label visible, we have to use the pack() method.
The code for the entire application:
# create a window and a label with image # Giovanni Gatto: http://pythonprogramming.altervista.org # 29/07/2018 - Give me credit showing these comments import tkinter as tk #The Window root = tk.Tk() #the label label = tk.Label(root, text="My label is this") label.pack() # the Loop root.mainloop()
An alternative way to add arguments to the widgets:
#the label label = tk.Label(root) label['text'] ="My label is this" label.pack()
Add some color to the label and change font
# label with color and font import tkinter root = tkinter.Tk() root.geometry("400x200+400+200") label = tkinter.Label(root, font="Arial 20") label['text'] = "My Label" label['bg'] = 'yellow' label.pack() root.mainloop()
An example
In the following example, the code will make change the color of the background when someone clicks on the window.
import tkinter as tk import random # video nr. 4 def changecolor(event): "Change the color of the window" # this changes the title # this changes the color root['bg'] = random.choice(['red', 'yellow', 'blue', 'orange', 'gray', 'black']) root.title(root['bg']) root = tk.Tk() root.title("MyApp") root.geometry("400x300+100+100") # this bind the button click to the window root.bind("", changecolor) label = tk.Label(root, text="This is a label") label['bg'] = 'yellow' label.pack() root.mainloop()
Random and choice