The first 4 Chapter Label control (Label)
The main function of the label control is to display text or pictures . If no size is specified when creating the label control , Control will automatically calculate the size based on the content to be displayed . Label controls can display multiple lines of text , It can also display text and pictures at the same time . See the following instructions for specific usage .
4.1 Creation of label control
4.1.1 Single line text
import tkinter as tk
root=tk.Tk()
root.geometry('300x240')
b1 = tk.Label(root,text=' I'm a label ')
b1.pack()
root.mainloop()
result :
4.1.2 Display images
The main function of the tag is to display the text . But labels can also be used to display images . at present tkinter Library only supports PGM, PPM, GIF, PNG Format . Pictures in other formats need to be converted .
import tkinter as tk
root=tk.Tk()
root.geometry('300x240')
p = tk.PhotoImage(file='a.gif')
b1 = tk.Label(root,image=p)
b1.pack()
root.mainloop()
result :
4.1.3 Images and text
You can also add text to this picture :
import tkinter as tk
root=tk.Tk()
root.geometry('300x240')
p = tk.PhotoImage(file='a.gif')
b1 = tk.Label(root,image=p,text=' caption ',
compound='center',fg='yellow')
b1.pack()
root.mainloop()
result :
4.1.4 Multiline text
Sometimes there are many words , It cannot be displayed in one line , Or it is more beautiful to use multiple lines . The first method is to manually insert ’\n’ To wrap , The second way is to use wraplength Option to Auto Branch .
import tkinter as tk
root=tk.Tk()
root.geometry('300x240')
b1 = tk.Label(root,
text=' first line \n The second line \n The third line ')
b1.pack()
root.mainloop()
result :
2. wraplength
import tkinter as tk
root=tk.Tk()
root.geometry('300x240')
b1 = tk.Label(root,
text=' This is a long line of text ,\
We can use wraplength To wrap lines automatically ',
wraplength=200)
b1.pack()
root.mainloop()
result :
explain :wraplength Is in pixels .