Python3 Tkinter-Button
2019-03-16 本文已影响0人
zmqqq
1.绑定事件处理函数
from tkinter import *
def hello():
print('Hello!')
root=Tk()
button=Button(root,text='click me!',command=hello)
button.pack()
root.mainloop()
![](https://img.haomeiwen.com/i16468855/66f2c27c7815b75a.png)
2.按钮样式
from tkinter import *
def hello():
print('Hello!')
root=Tk()
button1=Button(root,text='click me!',command=hello,relief=FLAT)
button1.pack()
button2=Button(root,text='click me!',command=hello,relief=GROOVE)
button2.pack()
button3=Button(root,text='click me!',command=hello,relief=RAISED)
button3.pack()
button4=Button(root,text='click me!',command=hello,relief=RIDGE)
button4.pack()
button5=Button(root,text='click me!',command=hello,relief=SOLID)
button5.pack()
button6=Button(root,text='click me!',command=hello,relief=SUNKEN)
button6.pack()
root.mainloop()
![](https://img.haomeiwen.com/i16468855/08ec1e0ff923a904.png)
3.图像
button也有bitmap,compound
4.焦点
from tkinter import *
def hello():
print('Hello!')
def b2(event):
print(event,' is clicked.')
root=Tk()
button1=Button(root,text='click me!',command=hello)
button1.pack()
button2=Button(root,text='click me!')
button2.bind('<Return>',b2)
button2.pack()
button2.focus_set()
button1.focus_set()
root.mainloop()
![](https://img.haomeiwen.com/i16468855/e474dfba2c5fcb95.png)
5.宽高
b.configure=(width=30,heigth=100)
也可在定义的时候确定
6.Button文本在控件上显示的位置
from tkinter import *
def hello():
print('Hello!')
root=Tk()
button1=Button(root,text='click me!',command=hello,anchor='ne',width=30,height=4)
button1.pack()
root.mainloop()
![](https://img.haomeiwen.com/i16468855/514f2395e2be0f22.png)
n(north),s(south),w(west),e(east),ne(north east),nw,se,sw
7.改变颜色
from tkinter import *
def hello():
print('Hello!')
root=Tk()
button1=Button(root,text='click me!',command=hello,fg='red',bg='blue')
button1.pack()
root.mainloop()
![](https://img.haomeiwen.com/i16468855/0789cc511c0a2271.png)
8.边框
from tkinter import *
def hello():
print('Hello!')
def b2(event):
print(event,' is clicked.')
root=Tk()
for b in [0,1,2,3,4]:
Button(root,text=str(b),bd=b).pack()
root.mainloop()
![](https://img.haomeiwen.com/i16468855/9fa0bf6fd0f32bb1.png)
9.状态
from tkinter import *
def hello():
print('Hello!')
def b2(event):
print(event,' is clicked.')
root=Tk()
for r in ['norma','active','disabled']:
Button(root,state=r,text=r).pack()
root.mainloop()
![](https://img.haomeiwen.com/i16468855/637411b6a0e744ab.png)
10.绑定变量
from tkinter import *
root=Tk()
def change():
if b['text']=='text':
v.set('change')
else:
v.set('text')
v=StringVar()
b=Button(root,textvariable=v,command=change)
v.set('text')
b.pack()
root.mainloop()
![](https://img.haomeiwen.com/i16468855/29c8321b488bfecc.png)
/w/1240)