Table of contents
introduce
In fact, tkinter has many functions, and there is no problem at all in using it to make a beautiful window. In this issue, let's take a look at the button control.
make a button
First, we need a button. Create a window and put the button on it:
import tkinter
root = tkinter.Tk()
button = tkinter.Button(root) #创建一个按钮
button.pack() #把按钮放在窗口上
root.mainloop()
It's a pity that there is nothing on the short button. . .
properties of the button
text
This is the text displayed on the button.
import tkinter
root = tkinter.Tk()
button = tkinter.Button(root,text="Hello World") #创建一个按钮,上面写 Hello World
button.pack() #把按钮放在窗口上
root.mainloop()
color
Buttons can also be colored. You can express it in English words, or you can use colors in HEX format. There are two colors, one is the font color, use fg
or foreground
as the attribute name; the other is the background color, use bg
or background
as the attribute name.
import tkinter
root = tkinter.Tk()
button1 = tkinter.Button(root,text="Hi!",fg="red",bg="blue") #红色字体,蓝色背景,用英语单词代替颜色
button1.pack() #把按钮放在窗口上
button2 = tkinter.Button(root,text="Hi!",fg="#00ff00",bg="#0000ff") #绿色字体,蓝色背景,用HEX格式的颜色
button2.pack()
#其实这么写也可以:
#button2 = tkinter.Button(root,text="Hi!",foreground="#00ff00",background="#0000ff")
#但这样写有点麻烦,你觉得呢?
root.mainloop()
Haha this color scheme is really hell!
font
Fonts are passed in as an array. The first item of the array is the font, and the second item is the font size. If the font cannot be found, tkinter will not report an error, but will use the default font instead.
import tkinter
root = tkinter.Tk()
button = tkinter.Button(root,text="Hi!",font=("Arial",50,"roman")) #字体为Arial,字号为50,正体字,也可以不指定样式,如font=("Arial",50)
#若不需要设置字体大小和字体样式,也可以直接写为:
#button = tkinter.Button(root,font="Arial")
button.pack() #把按钮放在窗口上
root.mainloop()
There are several font styles:
Key words | style |
---|---|
roman | normal characters |
italic | italics |
bold | Bold |
underline | underline |
overstrike | Bar off |
length and width
import tkinter
root = tkinter.Tk()
button1 = tkinter.Button(root,text="Hi!",width=5) #宽为5
button1.pack() #把按钮放在窗口上
button2 = tkinter.Button(root,text="Hi!",height=5) #长为5
button2.pack() #把按钮放在窗口上
button3 = tkinter.Button(root,text="Hi!",height=5,width=5) #长宽都为5
button3.pack() #把按钮放在窗口上
root.mainloop()
Hey, it's a bit ugly. . .
But why is my last button clearly set to be 5 in length and width, but not a square? This is because the length and width of the tkinter Button are not calculated in terms of pixels or fixed lengths (it should be the length and width of its font).
align
If the text on the button has many lines, it can be set to be centered, left or right.
import tkinter
root = tkinter.Tk()
string = """水调歌头
【宋】 苏轼
丙辰中秋,欢饮达旦,大醉,作此篇,兼怀子由。
明月几时有?把酒问青天。不知天上宫阙,今夕是何年。我欲乘风归去,又恐琼楼玉宇,高处不胜寒。起舞弄清影,何似在人间。
转朱阁,低绮户,照无眠。不应有恨,何事长向别时圆?人有悲欢离合,月有阴晴圆缺,此事古难全。但愿人长久,千里共婵娟。
"""
button1 = tkinter.Button(root,text=string,justify=tkinter.LEFT) #靠左
button1.pack() #把按钮放在窗口上
button2 = tkinter.Button(root,text=string,justify=tkinter.RIGHT) #靠右
button2.pack() #把按钮放在窗口上
button3 = tkinter.Button(root,text=string,justify=tkinter.CENTER) #居中
button3.pack() #把按钮放在窗口上
root.mainloop()
cursor
Cursors come in many styles. There is a lot of content, so let’s introduce it briefly here, and I will write a special article for the rest of the content when I find time.
import tkinter
root = tkinter.Tk()
button = tkinter.Button(root,text="Hi!",cursor="watch") #光标放在按钮上后转圈
button.pack() #把按钮粘到窗口上
root.mainloop()
The default mouse style is arrow (arrow), in addition to some other mouse styles, such as xterm and so on.
state
General tkinter controls have two commonly used states: normal (Normal), disabled (Disabled), and some less commonly used ones, such as read-only (Readonly) and active (Active), which are skipped here.
import tkinter
root = tkinter.Tk()
button1 = tkinter.Button(root,text="Normal",state=tkinter.NORMAL) #正常
button1.pack() #把按钮放在窗口上
button2 = tkinter.Button(root,text="Disabled",state=tkinter.DISABLED) #禁用,无法点击按钮
button2.pack() #把按钮放在窗口上
root.mainloop()
Disabled buttons are grayed out by default and cannot be clicked. However, you can also set the font color when disabled disabledforeground
, and the usage fg
is similar to attributes (but it seems that you cannot set the background color when disabled). like:
button = tkinter.Button(root,text="Disabled",state=tkinter.DISABLED,disabledforeground="green") #禁用时的字体是绿油油的
Order
After the button is pressed, what function does it need to have? This is the soul of the button. This is where attributes command
come in handy.
import tkinter
def click():
print("Hello World!")
root = tkinter.Tk()
button = tkinter.Button(root,text="Click me!",command=click) #点击之后运行先前定义的click函数
button.pack() #把按钮放在窗口上
root.mainloop()
frame
There are several types of borders: flat
, groove
, raised
, ridge
, solid
, sunken
; let’s take a look at the effect together!
import tkinter
root = tkinter.Tk()
relief = ["flat","groove","raised","ridge","solid","sunken"] #不同的样式
for i in relief:
button = tkinter.Button(root,text=i,relief=i) #每个样式来一个按钮
button.pack() #把每个样式的按钮放在窗口上
root.mainloop()
With the border style, we can also set the thickness of the border: bd
or borderwidth
.
import tkinter
root = tkinter.Tk()
button = tkinter.Button(root,text="Hi!",bd=20) #厚厚的一层边框
button.pack() #把按钮放在窗口上
root.mainloop()
picture
It would be boring if there was only text on a button. We can also put an image on the button:
import tkinter
root = tkinter.Tk()
photo = tkinter.PhotoImage(file="laugh.png") #加载一张图片
button = tkinter.Button(root,image=photo) #设置图片
button.pack() #把按钮贴在窗口上
root.mainloop()
In fact, it should be possible to write like this:
button = tkinter.Button(root,image="laugh.png")
However, there will always be some inexplicable errors, such as:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.8/tkinter/__init__.py", line 2650, in __init__
Widget.__init__(self, master, 'button', cnf, kw)
File "/usr/lib/python3.8/tkinter/__init__.py", line 2572, in __init__
self.tk.call(
_tkinter.TclError: image "laugh.png" doesn't exist
And when I use PhotoImage to load pictures, there is no problem, so it is not recommended to write like this, it is better to load pictures in advance instead of throwing them all to the button.
And if you want text and pictures to coexist, you can't be simple button = tkinter.Button(root,text="Hello",image=picture)
, otherwise you will find that the button has only pictures but no text. At this time, another attribute is needed: compound
, which controls the position of pictures and text.
value | mean |
---|---|
CENTER | Overlay text in the middle of the image |
BOTTOM | Show image below text |
LEFT | Show image to the left of the text |
RIGHT | Show image to the right of the text |
TOP | display image above text |
NONE | wooden text |
import tkinter
root = tkinter.Tk()
photo = tkinter.PhotoImage(file="laugh.png") #加载一张图片
compound = [tkinter.CENTER,tkinter.BOTTOM,tkinter.LEFT,tkinter.RIGHT,tkinter.TOP,tkinter.NONE]
for i in range(len(compound)):
button = tkinter.Button(root,image=photo,text=compound[i],compound=compound[i]) #按钮
button.grid(row=int(i / 2),column=i % 2) #把按钮贴在窗口上
root.mainloop()
modify properties
After setting up the button, you can change its properties. You can change the color and font. Just use the configure function of the button.
import tkinter
root = tkinter.Tk()
button = tkinter.Button(root,image=photo,text="Hello!") #按钮
button.pack() #把按钮贴在窗口上
button.configure(text="Hi!",font=("Consolas",50)) #将按钮上的文字改为"Hi!",再将字体设置为Consolas,字体大小50
#configure 和 config 都可以,
#button.config(text="Hi!",font=("Consolas",50)) 效果一样
root.mainloop()
Summarize
The above are most of the properties of the button. Let's review it together:
Attributes | significance |
---|---|
text | display text on button |
fg or foreground | font color |
bg or background | background color |
font | Button font, passed in as a tuple or string |
justify | Text centered (Center), left (Left) or right (Right) |
cursor | The style when the cursor is placed over the button |
state | Button state, such as disabled (Disabled), normal (Normal) |
disabledforeground | font color when disabled |
command | Command, which is the command to execute when the button is pressed |
relief | border style |
bd or borderwidth | border thickness |
image | For the picture displayed on the button, it is best to load PhotoImage in advance, otherwise errors may occur |
compound | Relative position when pictures and text coexist |
import tkinter
root = tkinter.Tk()
button = tkinter.Button(root,text="Hello World") #创建一个按钮,上面写 Hello World
button = tkinter.Button(root,text="Hi!",fg="red",bg="blue") #红色字体,蓝色背景,用英语单词代替颜色
button = tkinter.Button(root,text="Hi!",fg="#00ff00",bg="#0000ff") #绿色字体,蓝色背景,用HEX格式的颜色
button = tkinter.Button(root,text="Hi!",font=("Arial",50,"roman")) #字体为Arial,字号为50,正题字
button = tkinter.Button(root,font="Arial") #字体Arial,默认字号,默认字体样式
button = tkinter.Button(root,text="Hi!",width=5) #宽为5
button = tkinter.Button(root,text="Hi!",height=5) #长为5
button = tkinter.Button(root,text="Hi!",height=5,width=5) #长宽都为5
string = """水调歌头
【宋】 苏轼
丙辰中秋,欢饮达旦,大醉,作此篇,兼怀子由。
明月几时有?把酒问青天。不知天上宫阙,今夕是何年。我欲乘风归去,又恐琼楼玉宇,高处不胜寒。起舞弄清影,何似在人间。
转朱阁,低绮户,照无眠。不应有恨,何事长向别时圆?人有悲欢离合,月有阴晴圆缺,此事古难全。但愿人长久,千里共婵娟。
"""
button = tkinter.Button(root,text=string,justify=tkinter.LEFT) #靠左
button = tkinter.Button(root,text=string,justify=tkinter.RIGHT) #靠右
button = tkinter.Button(root,text=string,justify=tkinter.CENTER) #居中
button = tkinter.Button(root,text="Hi!",cursor="watch") #光标放在按钮上后转圈
button = tkinter.Button(root,text="Normal",state=tkinter.NORMAL) #正常
button = tkinter.Button(root,text="Disabled",state=tkinter.DISABLED) #禁用,无法点击按钮
button = tkinter.Button(root,text="Disabled",state=tkinter.DISABLED,disabledforeground="green") #禁用时的字体是绿油油的
def click():
print("Hello World!")
button = tkinter.Button(root,text="Click me!",command=click) #点击之后运行先前定义的click函数
button = tkinter.Button(root,text="Groove",relief="groove") #不同边框样式的按钮
button = tkinter.Button(root,text="Hi!",bd=20) #厚厚的一层边框
photo = tkinter.PhotoImage(file="laugh.png") #加载一张图片
button = tkinter.Button(root,image=photo) #设置图片
button = tkinter.Button(root,image=photo,text="Center",compound=tkinter.CENTER) #图片位置
button.configure(text="Hi!",font=("Consolas",50,"roman"))
button.pack() #按钮放在窗口上
root.mainloop()
Thank you for reading, your praise is my biggest motivation!