Tkinter图形界面

首先导入模块    from  tkinter inport  *

  • Label
  • Frame
  • Entry
  • Text
  • Button
  • Listbox
  • Scrollbar

以上是几个常用的控件,记住每个控件后面都必须加上pack()否则无法显示

1 from tkinter import *
2 
3 root = Tk()
4 root.title('hello world')  # 窗口蓝的标题
5 root.geometry('600x600')  # 设置初始窗口的大小
6 root.resizable(width=True,height=True)  # 设置长高是否可变
7 root.mainloop()   # 进入消息循环

1.Lable  控件的使用方法。

用法:Label(根对象,【属性列表】)

属性:

  • text    要现实的文本
  • bg    背景颜色
  • font    字体(颜色, 大小)
  • width  控件宽度
  • height 控件高度

代码

1 from tkinter import *
2 root = Tk()
3 root.title('hello world')
4 root.geometry('600x600')
5 root.resizable(width=True,height=True)
6 l = Label(root,text = '你好',bg = 'red'.encode(),width=5,height = 2)
7 l.pack(side =LEFT)
8 root.mainloop()

2.Frame 控件使用的方法

说明:在屏幕上创建一块矩形区域,多作为容器来布局窗体

用法:Frame(根对象,【属性列表】)

 1 from tkinter import *
 2 
 3 root = Tk()
 4 root.title('hello world')
 5 root.geometry('600x600')
 6 root.resizable(width=True,height=True)
 7 Label(root,text = '你好',font = ('Arial',20)).pack()
 8 frm = Frame(root)  # 实例化一个框架对象
 9 frm_l = Frame(frm)  # 在实例化框架里面再创建一个框架
10 Label(frm_l,text = '厚德',font = ('Arial',15)).pack(side=TOP)  # 创建第一个标签
11 Label(frm_l,text = '博学',font = ('Arial',15)).pack(side=TOP)  # 创建第二个标签
12 frm_l.pack(side=LEFT)  # 使这个框架靠左边(如果同一行右边有东西的话,就靠左)
13 frm_r = Frame(frm)  
14 Label(frm_r,text = '敬业',font = ('Arial',15)).pack(side = TOP)
15 Label(frm_r,text = '奉献',font = ('Arial',15)).pack(side = TOP)
16 frm_r.pack(side=RIGHT)
17 frm.pack()  # 框架控件也需要调用pack()方法
18 root.mainloop()

3.Entry

说明:创建单行文本框

用法:

  •   创建:lb =Entry(根对象, [属性列表])
  •   绑定变量 var=StringVar()    lb=Entry(根对象, textvariable = var)
  •   获取文本框中的值   var.get()
  •   设置文本框中的值   var.set(item1)
 1 from tkinter import *
 2 
 3 root = Tk()
 4 root.title('hello world')
 5 root.geometry('200x200')
 6 root.resizable(width=True,height=True)
 7 var = StringVar()  # 创建变量
 8 e = Entry(root,textvariable = var)
 9 var.set('hello')  #预先在文本框显示的文本
10 e.pack()
11 root.mainloop()

4.Text

说明:向该空间输入文本

用法:

t = Text(根对象)

  插入:t.insert(mark, 内容)

  删除:t.delete(mark1, mark2)

  其中,mark可以是行号,或者特殊标识,例如

  • INSERT:光标的插入点CURRENT:鼠标的当前位置所对应的字符位置
  • END:这个Textbuffer的最后一个字符
  • SEL_FIRST:选中文本域的第一个字符,如果没有选中区域则会引发异常
  • SEL_LAST:选中文本域的最后一个字符,如果没有选中区域则会引发 异常
 1 from tkinter import *
 2 
 3 root = Tk()
 4 root.title('hello world')
 5 root.geometry('200x200')
 6 root.resizable(width=True,height=True)
 7 t = Text(root)
 8 t.insert(2.0,'hello\n')
 9 t.insert(5.0,'hahahha')
10 t.pack()
11 root.mainloop()

5.Button

说明:创建按钮

用法:

Button(根对象,【属性列表】)

 1 root = Tk()
 2 root.title('hello world')
 3 root.geometry('200x200')
 4 def printhello():
 5     t.insert(1.0,'hello\n')
 6 
 7 t = Text(root)
 8 t.pack()
 9 Button(root,text = 'submit',command = printhello).pack()
10 root.mainloop()

猜你喜欢

转载自www.cnblogs.com/ch2020/p/12729421.html