python tkinter_一小时掌握基本知识(上)

本文旨在帮助已有Python基础的读者快速掌握tkinter的基本知识,包括Label、Button、Entry、Checkbutton、Radiobutton、Listbox、Scale和Spinbox等8个组件的使用。通过实例代码和关键属性的解释,读者可以了解如何创建和定制这些组件,实现简单的界面编程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

**1. Label
2. Button
3. Entry
4. Checkbutton
5. Radiobutton
6. Listbox
7. Scale
8. Spinbox**

python tkinter比较容易掌握,所以本博文旨在让已经有python基础的人用最短的时间掌握关于py tkinter的基本知识,从而快速进入自己的界面编程

这一篇主要包括上面8个知识点,当你快速看下来的时候,一定要将这里的所有代码运行一遍,有必要则适当修改,看运行的改变从而更好掌握。代码不长(这里贴的代码基于python3,用python2则把tkinter改成Tkinter)

1.Label:


知识总结:

文本内容

text = label_text

指定内置位图

bitmap = ‘error’
其他内置位图:
* hourglass
* info
* questhead
* question
* warning
* gray12
* gray25
* gray50
* gray75

颜色:
背景色:bg = ‘blue’/’#ff0000’
前景色:fg
Red
Green
Blue
Yellow
LightBlue

规格:

高度:height
宽度:width

边框padding

padx
pady

延展:
fill = BOTH/X/Y/None水平/竖直延展

字体:

Times Courier Helvetica( font family )
normal bold roman italic underline overstrike( or combinations like: bold italic )

文本图像位置

compound: 指定文本(text)与图像(bitmap/image)是如何在 Label 上显示,缺省为 None,
当指定center时,文本(text)将被覆盖,只显示图像了。可以使用的值:
left: 图像居左
right: 图像居右
top: 图像居上
bottom:图像居下
center:文字覆盖在图像上

多行显示控制

wraplength: 指定多少单位后开始换行
justify: 指定多行的对齐方式
ahchor: 指定文本(text)或图像(bitmap/image)在 Label 中的显示位置
e/w/n/s/ne/se/sw/sn/center
布局如下图
nw n ne
w center e
sw s se


代码:

from tkinter import *
root = Tk()
root.title('label test')
label = Label(
    root,
    bg = 'lightblue',
    fg = 'red',
    font = ('times',15,'bold'),
    text = 'this is my first label.welcome to python tkinter',
    width = 15 ,
    height = 8,
    wraplength = 120,
    anchor = 'n',
    justify = 'left')
label.pack(padx = 15,pady = 20,fill = BOTH)
bm = PhotoImage(file = 'G:/file_code/sublime/temp.png')
label2 = Label(
    root,
    text = 'an image',
    compound = 'top',
    image = bm)
label2.pack()
label3 = Label(root,bitmap = 'error',text = 'error bitmap',compound = 'left').pack(fill = X)
root.mainloop()

运行截图:
这里写图片描述


2.Button:


知识总结:

文本

text = button_name

颜色

bg/fg

外观

flat, groove, raised, ridge, solid, sunken
relief = FLAT

状态

state:指定组件状态:
正常 normal
激活 active
禁用 disabled

绑定变量

textvariable = variable_name
variable_name.get()取text的值
variable_name.set(‘new_text_name’)设置text的值

位图/图像

bitmap = 位图
image = image_object

事件处理函数

command = func_name
或者
button_name.bind(“”,func_name) func_name(event)须带参数,传递事件消息


代码:

from tkinter import *
root = Tk()
v = StringVar()
v.set('mybutton')
def print_button_name():
    print(v.get())
    if v.get() =='mybutton':
        v.set('yourbutton')
        name['anchor'] = 'n'
    else:
        v.set('mybutton')
        name['anchor'] = 's'
name =Button(root,bd = 10, text = 'mybutton',textvariable = v, state = 'active',anchor = 's',width = 20 , height = 2, bg = 'lightblue', fg = 'red', relief = RAISED, font = ( 'Helvetica',15,'italic'), command = print_button_name)
name.pack()
for i in [ 'top','right','bottom','left','center']:
    Button(root, text = i, compound = i, bitmap = 'error').pack()

im = PhotoImage(file = 'G:/file_code/sublime/temp.png')
for i in [ 'top','right','bottom','left','center']:
    Button(root, text = i, compound = i, image = im).pack()
root.mainloop()


运行截图:
这里写图片描述


3.Entry:


设置Entry的状态=’readonly’

Entry 的属性值可以使用的也为 normal/active/disabled,’readonly’与 disabled 一样

设置默认字符显示

show = ‘*’ 密码输入

其他属性

其他的属性 fg/bg/relief/width/height/justify/state 使用方法与 Button 相同
没有height/anchor属性


from tkinter import *
root = Tk()
e1 = StringVar()
st = ['normal','disabled','readonly']
for s in st:
    entry1 = Entry(root,textvariable=e1,state=s,width = 20 , bg = 'lightblue',fg = 'red',justify = 'left',relief = RAISED,font = ('times', 20 , 'italic'))
    e1.set('input your text')
    entry1.pack(padx = 15,pady = 15)
e2 = StringVar()
entry2 = Entry(root,textvariable = e2,show = '*',bg = 'yellow',relief = RAISED,font = ('times', 20 , 'italic'))
e2.set('password')
entry2.pack(padx = 20 ,pady = 20)

def change(content = None):
    key = entry3.get()
    sv.set('['+key+']')
    print(key)
sv = StringVar()
entry3 = Entry(root,textvariable=sv,font = ('times', 20 , 'italic'))
entry3.bind('<Return>',change) #按enter建触发
entry3.pack(padx = 15 ,pady = 15)
root.mainloop()

运行截图:
这里写图片描述


4.Checkbutton:


onvalue = ’ ‘, #设置 On 的值
offvalue = ’ ‘, #设置 Off 的值

from tkinter import *
root = Tk()
def callCB():
    if sv.get()=='on':
        sv.set('off')
    else:
        sv.set('on')

sv = StringVar()
lb = Label(root,textvariable=sv,font='times'+'30'+'normal')
sv.set('off')
lb.pack(side='left',anchor='nw')
cb = Checkbutton(root,text='on/off',command=callCB,width = 4 ,height = 2 , fg = 'red', bg = 'lightblue')
cb.pack(side='left',anchor='nw',padx = 5, pady = 5)


sta = IntVar()
def callCButton():
    print(sta.get())
Checkbutton(root,variable=sta,text='checkbutton value1',command=callCButton, relief = RAISED).pack(anchor='w',padx = 5,pady = 5)

onoff = StringVar()
onoff.set(0)
def callonoff():
    print(onoff.get())

Checkbutton(root,variable = onoff, text = 'checkbutton value2',
            onvalue='on',offvalue='off',
            command=callonoff).pack()


root.mainloop()

这里写图片描述


5.Radiobutton:


value相同完全一样
value相同绑定相同事件函数则点击时只调用一次函数
indication = 0 / 1 外观效果

from tkinter import *
root = Tk()
Radiobutton(root,text='python' ).pack()
Radiobutton(root,text='tkinter').pack()
Radiobutton(root,text='widget' ).pack()

v = IntVar()
v.set(1)
for i in range(3):
    Radiobutton(root,variable=v,text='python',value=i,width = 7,height = 2,fg = 'red',bg = 'lightgreen').pack(pady = 3)

vLang = IntVar()
vOS = IntVar()
vLang.set(1)
vOS.set(2)

for var in [vLang,vOS]:
    for i in range(3):
        Radiobutton(root,variable=var,value=i,text='python'+str(i),fg = 'red',bg = 'lightblue').pack(pady = 3)

idon = IntVar()
idon.set(1)
for i in range(3):
    Radiobutton(root,variable=idon,indicatoron=0,text = 'hello',value=i,width = 5,height = 2,fg = 'red',bg = 'lightblue').pack()


root.mainloop()

这里写图片描述


6.Listbox:


selectmode = MUTIPLE支持多选,类似Checkbutton
selectmode = BROWSE支持鼠标拖动选中区域
selectmode = SINGLE不支持鼠标拖动选中区域
selectmode = EXTENDED支持shift/ctrl操作选择

末尾插入

lb.insert(END,item)

只添加一个 item 将[]作为一个 item

lb.insert(0,[‘linux’,’windows’,’unix’])

添加三个 item,每个 string 为一个 item

lb.insert(0,’linux’,’windows’,’unix’)

删除

.delete(first)
.delete(first,last)
.delete(0,END)删除全部

多项选择,多项取消

.selection_set(first,last)
.selection_clear(first,last)

item个数

.size()

返回指定索引的items

.get(first)
.get(first,last)

绑定变量

v= StringVar()
lb[‘listvariable’] = v
可以用v.get()得到list的items值,返回一个tuple
可以用v.set(tuple)更改list的items值

返回当前选中的items

.curselection()

返回索引位置的items是否处于选中状态,true/false

.selection_includes(index)

绑定事件,不支持command,可以用bind绑定

def printList(event):
print (lb.get(lb.curselection()))
lb = Listbox(root,selectmode = EXTENDED)
lb.bind(‘’,printList)#左键双击

from tkinter import *
root = Tk()
v = StringVar()
def printList(event):
    print (lb.get(lb.curselection()))
lb = Listbox(root,listvariable = v,selectmode = EXTENDED,bg = 'lightblue',fg = 'red',width = 30,height = 20,font = ('time',15,'italic'))
lb.bind('<Double-Button-1>',printList)
for i in range(10):
    lb.insert(END,str(i))
lb.insert(0,['linux','windows','unix'])
lb.insert(0,'linux','windows','unix')
lb.insert(END,'hello world')
#lb.delete(END)
#lb.delete(0,3)
lb.selection_set(0,10)
lb.selection_clear(1,3)
print(lb.size())
print(lb.get(3,7))
print(lb.curselection())
print(lb.selection_includes(1))
print(lb.selection_includes(7))
print(v.get())
#v.set(('100','200'))
lb.pack(padx = 10,pady = 30)
root.mainloop()

这里写图片描述


7.Scale:


from_ = min_value 最小值
to = max_value 最大值
resolution = step_value 步长
orient = HORIZONTAL 水平方向,默认为垂直方向

回调函数

def print_scale(text):
print(‘text=’,text)
print(‘v=’,v.get())
属性command= print_scale

设置数字显示位数

digits = num

设置值,取值

.set(value)
.get()

from tkinter import *
root = Tk()
v = StringVar()
def print_scale(text):
    print('text=',text)
    print('v=',v.get())
s = Scale(root,from_ = -400,to = 400,resolution = 5,orient = HORIZONTAL,variable = v, command = print_scale, digits = 6, label = 'hello', width = 25,fg = '#885533',bg = 'lightblue')
s.set(50)
print(s.get())
s.pack()
root.mainloop()

这里写图片描述


8.Spinbox:


from_ = min_value最小值
to = max_value最大值
increment = step 类似scale的resolution

设置值

values = tuple

from tkinter import *
root = Tk()
v = StringVar()
def printSpin():
    print(v.get())
    print(sb.get())
# sb = Spinbox(root,values = (0,10,5,20,35,3),increment = 2)
# print(sb['values'])
sb = Spinbox(root,from_ = 100, to = 999, increment = 0.5,command = printSpin,width = 20,fg = 'red',bg = 'lightblue',textvariable = v)
sb.pack(padx = 10,pady = 10)
root.mainloop()

这里写图片描述


后续。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值