Python的Tkinter库总结(2)

版权声明:转载请联系邮箱[email protected] https://blog.csdn.net/weixin_42528077/article/details/82828250

tkinter基础知识

15种核心控件

tk.Button   #按钮; 
tk.Canvas   #画布组件,可以在其中绘制图形; 
tk.Radiobutton  #单选框; 
tk.Checkbutton  #复选框; 
tk.Entry    #文本框(单行); 
tk.Text      #文本框(多行); 
tk.Frame   #框架,将几个组件组成一组 
tk.Label    #标签,可以显示文字或图片; 
tk.Listbox   #列表框; 
tk.Menu    #菜单; 
tk.Menubutton  #它的功能完全可以使用Menu替代; 
tk.Message  #与Label组件类似,但是可以根据自身大小将文本换行; 
tk.Scale    #滑块;允许通过滑块来设置一数字值 
tk.Scrollbar  #滚动条,配合canvas, entry, listbox, and text窗口部件的标准滚动条; 
tk.Toplevel  #用来创建子窗口窗口组件。 

3种核心布局

widget.pack() #自适应的布局方案
widget.grid() #网格布局方案
widget.place() #按坐标的布局方案
pack布局的参数:
after    #将组件置于其他组件之后; 
before   #将组件置于其他组件之前; 
anchor    #组件的对齐方式,顶对齐’tk.N’,底对齐'tk.S’,左'tk.W',右'tk.E' ,中间'tk.CENTER',可以两个一起使用
side   #组件在主窗口的位置,可以为’top’,’bottom’,’left’,’right’(使用tk.TOP等); 
fill    #填充方式 (tk.Y垂直填充,tk.X水平填充,tk.BOTH为两边填充,None为不填充) 
expand   #1可扩展,0不可扩展 

示例如下:

from tkinter import *
root = Tk()
Button(root,text='A').pack(side=LEFT,expand=1,fill=Y)
Button(root,text='B').pack(side=TOP,expand=1,fill=BOTH)
Button(root,text='C').pack(side=RIGHT,expand=1,fill=NONE)
Button(root,text='D').pack(side=LEFT,expand=0,fill=Y)
Button(root,text='E').pack(side=TOP,expand=0,fill=BOTH)
Button(root,text='F').pack(side=BOTTOM,expand=YES)
Button(root,text='G').pack(anchor=CENTER)
root.mainloop()

窗口长成这样:
窗口

grid布局的参数
sticky    #决定一个组件从哪个方向开始(tk.N上,tk.W左,tk.S下,tk.E右)
column  #组件所在的列起始位置; 
columnspan  #组件的列宽(占用的列数); 
row    #组件所在的行起始位置; 
rowspan  #组件的行宽(占用的行数); 

示例如下:

from tkinter import *

root = Tk()
Label(root, text='用户名:').grid(row=0,column=0,sticky=W)
Entry(root).grid(row=0, column=1, sticky=E)

Label(root, text='密码:').grid(row=1, sticky=W)
Entry(root).grid(row=1, column=1, sticky=E)  # 输入框

Button(root, text='登陆').grid(row=2, column=1, sticky=E)

root.mainloop()

窗口长成这样:
窗口

place布局的参数
anchor  #组件对齐方式,同上;
x     #组件左上角的x坐标; 
y     #组件左上角的y坐标; 
relx  #组件相对于窗口的x坐标,应为0-1之间的小数; 
rely   #组件相对于窗口的y坐标,应为0-1之间的小数; 
#可以同时使用相对坐标和绝对坐标,此时组件为在相对坐标的基础上作绝对坐标的偏移
width  #组件的宽度; 
height  #组件的高度; 
relwidth  #组件相对于窗口的宽度,0-1之间; 
relheight  #组件相对于窗口的高度,0-1之间;

示例如下:

from tkinter import *

root = Tk()
root.geometry('200x400')
lb = Label(root, text='hello Place')
# lb.place(relx = 1,rely = 0.5,anchor = CENTER)
# 使用相对坐标(0.5,0.5)将Label放置到(0.5*sx,0.5.sy)位置上
v = IntVar()
for i in range(5):
    Radiobutton(
        root,
        text='Radio' + str(i),
        variable=v,
        value=i
    ).place(y=80 * i, anchor=NW)
root.mainloop()

窗口长成这样:
窗口

猜你喜欢

转载自blog.csdn.net/weixin_42528077/article/details/82828250