Tk+interface=Tkinter
import tkinter as tk
app=tk.Tk() #顶层窗口
thelabel=tk.Lable(app,text="demo")
thelabel.pack() #自动调节组件位置和大小
app.mainloop() #主时间循环,没有这句窗口不会显示,通常是程序最后一行代码。类似把程序控制权交给tkinter,如点击操 # 作,由tkinter响应。
高级应用:
把GUI封装成类
import tkinter as tk
class App:
def __init__(self,master):
frame=tk.Frame(master) #框架,把窗口分布布局
frame.pack()
self.hi_there=tk.Button(frame,text='',fg='blue',bg='black',commad=self.say_hi)
self.hi_there.pack(side=tk.LEFT,padx=10,pady=10)
def say_hi(self):
print('hello')
root=tk.Tk()
app=App(root)
root.mainloop()
Lable对象:文字、图片
from tkinter import *
# 导入tkinter模块的所有内容
root = Tk()
# 创建一个文本Label对象
textLabel = Label(root,
text="您所下载的影片含有未成年人限制内容,\n请满18岁后再点击观看!",
justify=LEFT,
padx=10)
textLabel.pack(side=LEFT)
# 创建一个图像Label对象
# 用PhotoImage实例化一个图片对象(支持gif格式的图片)
photo = PhotoImage(file="18.gif")
imgLabel = Label(root, image=photo)
imgLabel.pack(side=RIGHT)
mainloop()
图片作为背景,label实现:
from tkinter import *
root = Tk()
photo = PhotoImage(file="bg.gif")
theLabel = Label(root,
text="学Python\n到FishC",
justify=LEFT,
image=photo,
compound=CENTER,
font=("华康少女字体", 20),
fg="white"
)
theLabel.pack()
mainloop()
from tkinter import *
# 导入tkinter模块的所有内容
def callback():
var.set("吹吧你,我才不信呢~")
root = Tk()
frame1 = Frame(root)
frame2 = Frame(root)
# 创建一个文本Label对象
var = StringVar()
var.set("您所下载的影片含有未成年人限制内容,\n请满18岁后再点击观看!")
textLabel = Label(frame1,
textvariable=var,
justify=LEFT)
textLabel.pack(side=LEFT)
# 创建一个图像Label对象
# 用PhotoImage实例化一个图片对象(支持gif格式的图片)
photo = PhotoImage(file="18.gif")
imgLabel = Label(frame1, image=photo)
imgLabel.pack(side=RIGHT)
# 加一个按钮
theButton = Button(frame2, text="已满18周岁", command=callback)
theButton.pack()
frame1.pack(padx=10, pady=10)
frame2.pack(padx=10, pady=10)
mainloop()
justify 用法:
1. 定义如何对齐多行文本
2. 使用 “left”,“right” 或 “center”
3. 注意,文本的位置取决于 anchor 选项
4. 默认值是 “center”
compound 用法:
1. 控制 Label 中文本和图像的混合模式
2. 默认情况下,如果有指定位图或图片,则不显示文本
3. 如果该选项设置为 “center”,文本显示在图像上(文本重叠图像)
4. 如果该选项设置为 “bottom”,“left”,“right” 或 “top”,那么图像显示在文本的旁边(如 “bottom”,则图像在文本的下方)
5. 默认值是 NONE
textvariable 用法
1. Label 显示 Tkinter 变量(通常是一个 StringVar 变量)的内容
2. 如果变量被修改,Label 的文本会自动更新