按钮 案例图1:(根据 图自行写出代码练习 使用 Pycharm 2022.2.3 /Pycharm 3.10.8)后面有参考答案
from tkinter import *
def set():
print("Hello World!!!")
root = Tk()
root.geometry("400x200")
frame = Frame(root)
frame.pack()
button1 = Button(frame, text="按钮 确认", command=set)
button1.pack()
button2 = Button(frame, text="按钮 取消", command=root.quit) # command 取消的写法
button2.pack()
# fg 字体颜色 font 字体样式 按钮 bg 背景色 relief 样式
button3 = Button(frame, text = "按钮 字", command = set,
fg = "Blue", font = "黑体 14 underline",
bd = 2, bg = "light green", relief = "groove")
button3.pack()
root.mainloop()
按钮参数 参考 方案如下(中 英文):
属性 |
说明 |
anchor |
控制文本所在的位置,默认为中心位置(CENTER) |
activebackground |
当鼠标放在按钮上时候,按妞的背景颜色 |
activeforeground |
当鼠标放在按钮上时候,按钮的前景色 |
bd |
按钮边框的大小,默认为 2 个像素 |
bg |
按钮的背景色 |
command |
用来执行按钮关联的回调函数。当按钮被点击时,执行该函数 |
fg |
按钮的前景色 |
font |
按钮文本的字体样样式 |
height |
按钮的高度 |
highlightcolor |
按钮控件高亮处要显示的颜色 |
image |
按钮上要显示的图片 |
justify |
按钮显示多行文本时,用来指定文本的对齐方式,参数值有 LEFT/RIGHT/CENTER |
padx/pady |
padx 指定 x 轴(水平方向)的间距大小,pady 则表示 y轴(垂直方向)的间距大小 |
ipadx/ipady |
ipadx 指标签文字与标签容器之间的横向距离;ipady 则表示标签文字与标签容器之间的纵向距离 |
state |
设置按钮的可用状态,可选参数有NORMAL/ACTIVE/DISABLED,默认为 NORMAL |
text |
按钮控件要显示的文本 |
No. | Option | Description |
---|---|---|
1 | activebackground | The Background color when the cursor is over the button. |
2 | activeforeground | The Foreground color when the cursor is over the button. |
3 | bg | Background Color of the button |
4 | bd | Border size of frame in pixels. Default is 2. |
5 | command | Command to be executed when button is clicked. Typically set to a function call. |
6 | fg | foreground color |
7 | font | Text font for the button |
8 | height | Height of the button |
9 | highlightcolor | The text color when the widget is under focus. |
10 | image | Image to be displayed on the button. By default, image will replace the text. |
11 | justify | Changes the alignment of the text. Can be set to either LEFT, CENTER or RIGHT. |
12 | padx | padding to the left and right of the text. |
13 | pady | padding above and below the text. |
14 | relief | It specifies the type of the border. Default is Flat, other options include raised , flat , ridge , groove and sunken . |
15 | state | Default is NORMAL. DISABLED causes the button to gray out and go inactive. ACTIVE is the state of the button when mouse is over it. |
16 | underline | Default is -1. Set this option to under line the button text. |
17 | width | Width of the button |
18 | wraplength | If the value is set to a positive number, the text lines will be wrapped to fit within this length. |