首先,Tkinter是Python默认的GUI库,想IDLE就是用Tkinter设计出来的,因此直接导入Tkinter模块就可以啦

1 import tkinter

(1)Tkinter初体验:

 1 import tkinter as tk
2
3 # 创建一个主窗口,用于容纳整个GUI程序
4 root = tk.Tk()
5 # 设置主窗口对象的标题栏
6 root.title("NEW")
7 # 添加一个Label组件,Label组件是GUI程序中最常用的组件之一
8 # Label组件可以显示文本、图标或者图片
9 # 在这里我们让他们显示指定文本
10 theLabel = tk.Label(root, text="就是体验一下")
11 # 然后调用Label组建的pack()方法,用于自动调节组件自身的尺寸
12 theLabel.pack()
13 # 注意,这时候窗口还是不会显示的...
14 # 除非执行下面的这条代码!!!!!
15 root.mainloop()

显示结果:

升级上面程序:通常如果要写一个比较大的程序,那么应该先把代码给封装起来。在面向对象的编程语言中,就是封装成类

 1 import tkinter as tk
2
3 class App:
4 def __init__(self, root):
5 # 创建一个框架,然后在里面添加一个Button按钮组件
6 # 框架一般使用于在复杂的布局中起到将组建分组的作用
7 frame = tk.Frame(root)
8 frame.pack()
9 # 创建一个按钮组件,fg是foreground的缩写,就是设置前景色的意思
10 self.hi_there = tk.Button(frame, text="打招呼", fg="blue", command=self.say_hi)
11 self.hi_there.pack(side=tk.LEFT)
12
13 def say_hi(self):
14 print("互联网的广大朋友们大家好,我是初音未来!")
15
16 # 创建一个toplevel的根窗口,并把他作为擦参数实例化APP对象
17 root = tk.Tk()
18 app = App(root)
19 # 开始主事件循环
20 root.mainloop()

显示结果:

然后点击打招呼后会在控制台会输出  "互联网的广大朋友们大家好,我是初音未来! " 这句话

注意:可以通过修改pack()方法的side参数,side参数可以设置LEFT,RIGHT,TOP和TOTTOM四个方位,默认设置是side=tkinter.TOP.

     例如如上程序就修改了frame.pack(side=tk.LEFT)。

     还有一件事!!!如果你不想按钮挨着"墙角",可以通过设置pack()方法的padx和pady参数自定义按钮的偏移位置

     最后,就像你所看到的,按钮既然可以设置前景色,那么就一定可以设置背景色,bg参数就是啦,他是background的缩写

    

1 elf.hi_there = tk.Button(frame, text="打招呼", bg="red", fg="blue", command=self.say_hi) #此时按钮的背景色就成了红色

(2)Label组件(用于在界面上输出描述的标签,例如提示用户...):

 1 from tkinter import *
2
3 root = Tk()
4 # 创建一个文本Label对象,justify函数其实就是让下图中的两行文字左对齐啦
5 textLabel = Label(root, text="您所下载的影片含有未成年人限制内容,\n请满18岁后再点击观看!", justify=LEFT, padx=10)
6 textLabel.pack(side=LEFT)
7 # 创建一个图像Label对象,注意这里只支持gif格式的图片
8 photo = PhotoImage(file="D:/python/images/02.gif")
9 imgLabel = Label(root, image=photo)
10 imgLabel.pack(side=RIGHT)
11
12 mainloop()

显示结果:

嗯,学完了上面的一个Labe示例后,我们想一下,我们有时候是不是需要将图片和文字分开,例如将图片作为背景,文字显示在图片的上面,只需要设置compound选项即可:

1 from tkinter import *
2
3 root = Tk()
4 photo = PhotoImage(file="D:/python/images/nature.gif")
5 theLabel = Label(root, text="学Python\n到FishC", justify=LEFT, image=photo, compound=CENTER, font=("幼圆", 20), fg="white")
6 theLabel.pack()
7
8 mainloop()

显示结果:

(3)Button组件(就是实现一个按钮而已):

 1 from tkinter import *
2
3 def callback():
4 var.set("吹吧你,我才不信嘞!")
5
6 root = Tk()
7 frame1 = Frame(root)
8 frame2 = Frame(root)
9 # 创建一个文本Label对象
10 var = StringVar()
11 var.set("您所下载的影片含有未成年人限制内容,\n请满18岁后再点击观看!")
12 textLabel = Label(frame1, textvariable=var, justify=LEFT)
13 textLabel.pack(side=LEFT)
14 # 创建一个图形Label对象
15 # 用PhotoImage实例化一个图片对象(支持gif格式文件哦)
16 photo = PhotoImage(file="D:/python/images/02.gif")
17 imgLabel = Label(frame1, image=photo)
18 imgLabel.pack(side=RIGHT)
19 # 加一个按钮
20 theButton = Button(frame2, text="已满18周岁", command=callback)
21 theButton.pack()
22 frame1.pack(padx=10, pady=10)
23 frame2.pack(padx=10, pady=10)
24
25 mainloop()

显示结果:

当你点击已满18周岁按钮后就会出现:

(4)CheckButton组件(多选):

 1 from tkinter import *
2
3 root = Tk()
4 GIRLS = ["西施", "王昭君", "貂蝉", "杨玉环"]
5 v = []
6 for girl in GIRLS:
7 v.append(IntVar())
8 b = Checkbutton(root, text=girl, variable=v[-1])
9 b.pack(anchor=W)
10
11 mainloop()

显示结果:

注意:为了输出更加美观,在这里通过设置pack()方法的anchor选项就可以实现。anchor选项是用于置顶显示位置,可以设置为N,NE,E,SE,S,SW,W,NW,CENTER九个不同的值。

     相信地理学的不错的朋友一下子就反应过来了,他们正是东西南北的缩写。

(5)Radiobutton(单选):

1 from tkinter import *
2
3 root = Tk()
4 v = IntVar()
5 Radiobutton(root, text="One", variable=v, value=1).pack(anchor=W)
6 Radiobutton(root, text="Two", variable=v, value=2).pack(anchor=W)
7 Radiobutton(root, text="Three", variable=v, value=3).pack(anchor=W)
8
9 mainloop()

显示结果:

那么此时问题就来了,如果你添加的选项比较多的话那么你就得重复写Radiobutton函数,那将会是一件麻烦的事情,所以呢,循环处理将会是一个不错的方法!

 1 from tkinter import *
2
3 root = Tk()
4 LANGS = [("Python", 1), ("Per1", 2), ("Ruby", 3), ("Lua", 4)]
5 v = IntVar()
6 v.set(1)
7 for lang, num in LANGS:
8 b = Radiobutton(root, text=lang, variable=v, value=num)
9 b.pack(anchor=W)
10
11 mainloop()

显示结果:

注意:如果你不喜欢前面这个小圈圈,还可以改成按钮的形式:

1  b = Radiobutton(root, text=lang, variable=v, value=num, indicatoron=False)
2 b.pack(fill=X)

随之就变成了:

(6)LabelFrame组件(自我认为就是个Frame的美化):

 1 from tkinter import *
2
3 root = Tk()
4 group = LabelFrame(root, text="最好的脚本语言是?", padx=5, pady=5)
5 group.pack(padx=10, pady=10)
6 LANGS = [("Python", 1), ("Per1", 2), ("Ruby", 3), ("Lua", 4)]
7 v = IntVar()
8 v.set(1)
9 for lang, num in LANGS:
10 b = Radiobutton(group, text=lang, variable=v, value=num)
11 b.pack(anchor=W)
12
13 mainloop()

显示结果:

(7)Entry组件(就是平时所说的输入框):

1 from tkinter import *
2
3 root = Tk()
4 e = Entry(root)
5 e.pack(padx=20, pady=20)
6 e.delete(0, END)
7 e.insert(0, "默认字体...")
8
9 mainloop()

显示结果:

获取输入框里边的内容,可以使用Entry组件的get()方法。当然也可以将一个Tkinter的变量(通常是StringVar)挂钩到textvariable选项,然后通过变量的get()方法获取!!

下面就是一个简单的示例:

 1 from tkinter import *
2
3 root = Tk()
4 # Thinker总共提供了三种布局组件的方法:pack(),grid()和place()
5 # grid()方法允许你用表格的形式来管理组件的位置
6 # row选项代表行,column选项代表列
7 # 例如row=1,column=2表示第二行第三列(0表示第一行)
8 Label(root, text="作品:").grid(row=0)
9 Label(root, text="作者:").grid(row=1)
10 e1 = Entry(root)
11 e2 = Entry(root)
12 e1.grid(row=0, column=1, padx=10, pady=5)
13 e2.grid(row=1, column=1, padx=10, pady=5)
14
15 def show():
16 print("作品:<< % s>>" % e1.get())
17 print("作者:<< % s>>" % e2.get())
18 e1.delete(0, END)
19 e2.delete(0, END)
20
21 # 如果表格大于组件,那么可以使用sticky选项来设置组件的位置
22 # 同样你需要使用N,E,S,W以及他们的组合NE,SE,SW,NW来表示方位
23 Button(root, text="获取信息", width=10, command=show).grid(row=3, column=0, sticky=W, padx=10, pady=5)
24 Button(root, text="退出", width=10, command=root.quit()).grid(row=3, column=1, sticky=E, padx=10, pady=5)
25
26 mainloop()

显示结果(输入作品合作者后点击获取信息后,即可在控制台上看到红箭头所之内容,然后窗口你的输入清空):

还有一种情况那就是我们在输密码时候我们需要保密,所以呢我们用*代替你的密码输入即可,代码如下:

 1 from tkinter import *
2
3 root = Tk()
4 # Thinker总共提供了三种布局组件的方法:pack(),grid()和place()
5 # grid()方法允许你用表格的形式来管理组件的位置
6 # row选项代表行,column选项代表列
7 # 例如row=1,column=2表示第二行第三列(0表示第一行)
8 Label(root, text="User:").grid(row=0)
9 Label(root, text="Password:").grid(row=1)
10 e1 = Entry(root)
11 e2 = Entry(root, show="*")
12 e1.grid(row=0, column=1, padx=10, pady=5)
13 e2.grid(row=1, column=1, padx=10, pady=5)
14
15 def show():
16 print("User:<< % s>>" % e1.get())
17 print("Password:<< % s>>" % e2.get())
18 e1.delete(0, END)
19 e2.delete(0, END)
20
21 # 如果表格大于组件,那么可以使用sticky选项来设置组件的位置
22 # 同样你需要使用N,E,S,W以及他们的组合NE,SE,SW,NW来表示方位
23 Button(root, text="芝麻开门", width=10, command=show).grid(row=3, column=0, sticky=W, padx=10, pady=5)
24 Button(root, text="退出", width=10, command=root.quit()).grid(row=3, column=1, sticky=E, padx=10, pady=5)
25
26 mainloop()

显示结果:

另外,Entry组件还支持验证输入内容的合法性。例如输入框要求输入的是数字,用户输入了字母就属于非法输入。实现该功能,需要通过设置validate,validatecommand和invalidcommand三个选项。

首先启用验证的"开关"是validate选项,该选项可以设置的值如下表所示:

其次是为validatecommand选项指定一个验证函数,该函数只能返回True或False表示验证结果。一般情况下验证函数值需要知道输入框的内容即可,可以通过Entry组建的get()方法获得改字符串。

 1 from tkinter import *
2
3 root = Tk()
4
5 def test():
6 if e1.get() == "小甲鱼":
7 print("正确")
8 return True
9 else:
10 print("错误!")
11 e1.delete(0, END)
12 return False
13
14 v = StringVar()
15 e1 = Entry(root, textvariable=v, validate="focusout", validatecommand=test)
16 e2 = Entry(root)
17 e1.pack(padx=10, pady=10)
18 e2.pack(padx=10, pady=10)
19
20 mainloop()

显示结构:

(8)Listbox组件:

这个读者可以和单选和多选那个做个比较,此组件适用于提供的选项非常多的情况

 1 from tkinter import *
2
3 root = Tk()
4 # 创建一个空列表
5 theLB = Listbox(root, setgrid=True)
6 theLB.pack()
7 # 往列表里添加数据
8 for item in ["篮球", "足球", "乒乓球", "羽毛球"]:
9 theLB.insert(END, item)
10 theButton = Button(root, text="删除", command=lambda x=theLB: x.delete(ACTIVE))
11 theButton.pack()
12
13 mainloop()

显示结果:

选择选项后点击删除就可以删除该项啦!!!!!

(9)Scrollbar组件:

首先让我们看一个代码:

1 root = Tk()
2 # 创建一个空列表
3 theLB = Listbox(root, setgrid=True)
4 theLB.pack()
5 # 往列表里添加数据
6 for item in range(11):
7 theLB.insert(END, item)
8
9 mainloop()

显示结果:

你会发现10没了,只有当你滚动鼠标滚轴时才会出现,但是一般来说不给你提示你是不会想到滚动鼠标滚轴的哦,所以Scrollbar就诞生了

 1 from tkinter import *
2
3 root = Tk()
4 sb = Scrollbar(root)
5 sb.pack(side=RIGHT, fill=Y)
6 lb = Listbox(root, yscrollcommand=sb.set)
7 for i in range(1000):
8 lb.insert(END, str(i))
9 lb.pack(side=LEFT, fill=BOTH)
10 sb.config(command=lb.yview)
11
12 mainloop()

显示结果:

(10)Scale组件:

这个和Scrollbar类似,但是这个组件主要是通过滑块来表示某个范围内的一个数字的

 1 from tkinter import *
2
3 root = Tk()
4 Scale(root, from_=0, to=42).pack()
5 Scale(root, from_=0, to=200, orient=HORIZONTAL).pack()
6
7 mainloop()
8
9 from tkinter import *
10
11 root = Tk()
12 s1 = Scale(root, from_=0, to=42)
13 s1.pack()
14 s2 = Scale(root, from_=0, to=200, orient=HORIZONTAL)
15 s2.pack()
16
17 def show():
18 print(s1.get(), s2.get())
19
20 Button(root, text="获取位置", command=show).pack()
21
22 mainloop()

显示结果:

滑动它有控制台耶会有相应的输出

另一个示例:

 1 from tkinter import *
2
3 root = Tk()
4 Scale(root, from_=0, to=42).pack()
5 Scale(root, from_=0, to=200, orient=HORIZONTAL).pack()
6
7 mainloop()
8
9 from tkinter import *
10
11 root = Tk()
12 Scale(root, from_=0, to=42, tickinterval=5, length=200, resolution=5, orient=VERTICAL).pack()
13 Scale(root, from_=0, to=200, tickinterval=10, length=600, orient=HORIZONTAL).pack()
14
15 mainloop()

显示结果:

Python之GUI的最终选择(Tkinter)的更多相关文章

  1. GUI的最终选择 Tkinter(四):Entry、Listbox、Scrollbar和Scale组件

    Entry组件 Entry组件就是平时所说的输入框.输入框是程序员用到的最多的一个程序,例如在输入账号和密码的时候需要提供两个输入框,用于接收密码的输入框还会有星号将实际输入的内容隐藏起来. Tkin ...

  2. GUI的最终选择Tkinter模块初级篇

    一.Tkinter模块的基本使用 1)实例化窗口程序 import tkinter as tk app = tk.Tk() app.title("FishC Demo") app. ...

  3. GUI的最终选择 Tkinter(五):Text用法

    Text组件 绘制单行文本使用Label组件,多行选使用Listbox,输入框使用Entry,按钮使用Button组件,还有Radiobutton和Checkbutton组件用于提供单选或多选的情况, ...

  4. GUI的最终选择 Tkinter(一):Tkinter最初体验

    EasyGui就是一个简单的文字交互界面模块,从今天开始来开始学习Tkinter Tkinter是Python标准的Gui库,它实际是建立在Tk技术上的,Tk最初是为Tcl(一门工具名语言)所涉及的, ...

  5. GUI的最终选择 Tkinter(七):菜单Menu组件、Menubutton组件、OptionMenu组件

    Menu组件 今天说的Menu组件就是一些菜单组件,开始点点点... Tkinter提供了一个Menu组件,可以实现顶级菜单,下拉菜单和弹出菜单.由于底层是代码实现和优化的,所以不太建议通过按钮和其他 ...

  6. GUI的最终选择Tkinter模块练习篇

    一.Canvas画布练习 1)简单的绘制图框 from tkinter import * # 构建一个窗口 tk = Tk() # 画布 canvas= Canvas(tk,width=,height ...

  7. GUI的最终选择 Tkinter(三):Checkbutton组件和Radiobutton组件、LabelFrame组件

    Checkbutton组件 Checkbutton组件就是常见的多选按钮,而Radiobutton则是单选按钮 from tkinter import * root = Tk() v = IntVar ...

  8. GUI的最终选择 Tkinter(二):Label和Button组件

    Label组件 Lable组件是用于界面上输出描述的标签,例如提示用户“您下载的电影含有未成年人限制内容,请满18岁以后点击观看!”,先来上结果图: 在来看下它的代码: from tkinter im ...

  9. GUI的最终选择 Tkinter(九):事件

    Tkinter事件处理 Tkinter应用会花费大部分的时间在处理事件循环中(通过mainloop()方法进入),事件可以是触发的鼠标,键盘的操作,管理窗口触发的重绘事件(在多数情况下都是有用户间接引 ...

随机推荐

  1. C# ArcEngine TOCControl上实现右键

    第一种方法:使用contextMenuStrip控件 1.新建一个窗体AttributeTable,并定义一个全局变量mLayer,让主窗体里面的axMapControl1的layer传进来,从而获取 ...

  2. Python实现简单HTTP服务器(一)

    一.返回固定内容 # coding:utf-8 import socket from multiprocessing import Process def handle_client(client_s ...

  3. mysql jdbc操作

    import java.sql.*; import java.util.Map; public class Mysql { public static void main(String[] args) ...

  4. Python实现常用的逻辑数据结构

    逻辑数据结构包括:线形结构.树形结构.图形结构.集合:存储结构包括:顺序存储.链式存储.索引存储.散列存储. 同一种逻辑结构可以有四种存储结构,不同的存储结构增.删.查.改的速度不同.逻辑结构与存储结 ...

  5. 关于JS call apply 对象、对象实例、prototype、Constructor、__proto__

    关于call与apply的理解容易让人凌乱,这里有个方法可供参考 tiger.call(fox,arg1,arg2...) tiger.apply(fox,[arg1,arg2...]) 理解为 fo ...

  6. HandlerThread分析

    Handy class for starting a new thread that has a looper. The looper can then be used to create handl ...

  7. 001-Spring Cloud Edgware.SR3 升级最新 Finchley.SR1,spring boot 1.5.9.RELEASE 升级2.0.4.RELEASE注意问题点

    一.前提 升级前 => 升级后 Spring Boot 1.5.x => Spring Boot 2.0.4.RELEASE Spring Cloud Edgware SR3 => ...

  8. 完成向后台添加用户的ssm项目,完整版

    1:ssm框架整合 1.1添加maven依赖pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns: ...

  9. [vue]实现父子组件数据双向绑定

    参考: http://www.cnblogs.com/xxcanghai/p/6124699.html <!DOCTYPE html> <html lang="en&quo ...

  10. context、config

    Tomcat启动时已经创建了context,并使用它读取了web.xml中的参数,后台可以从context里获取参数 后台获取参数代码: ServletContext context = getSer ...