Python基础知识

Python

print()
print 参数:end 默认为 换行,即end = "\n"
可以不换行,即 end = ""
或指定结束,即 end = "abc"
#内建函数
"""
注释
"""

占位符:

  • %d 整数

  • %f 浮点型 %0.1f 保留一位

  • %s 字符串

包裹:


import copy #引入copy包裹
import random #引入random包裹
import functools #引入functools包裹,不常用的函数
import time
import os     系统  os.system("cls")
import os.path
import pickle
import csv

from urllib.request import *
import re

import tkinter as tk    

os:

  • os.system() 命令行控制台

  • os.listdir() 显示目录下的内容

  • os.mkdir() 创建文件夹

os.path:

  • os.path.isfile() 是否为文件

  • os.path.isdir() 是否为路径

内建函数:

  1. print()

  2. input()

  3. type()


    name = input("名字")
    print(name,":",type(name))

    名字123
    123 : <class 'str'>
  4. float()

  5. int()

  6. bin()

  7. hex()

  8. oct()

  9. id()查看变量的地址

  10. range(start,end,step) 创建序列 start 开始, end 结束, step 步进值

  11. ord('A') 转化单个字母

  12. chr(97) 'a' 转化为字符串


  13. name='张三'
    name.encode('utf8')
    int.from_bytes(name.encode('utf8'),xxxx='big')
  14.  

变量:

  1. 变量不需要先声明,直接赋值,直接使用

  2. 同时给多个变量赋值

  3. 命名:数字字母下划线组成,不能以数字开头,区分大小写,不能使用$

  4. 不支持 自增自减 a += 1;

  5. 变量名不可以是 关键字和保留字

数据类型:

1. 数字

  • 整数

    0b开头,二进制;0o开头,八进制;0x,十六进制;科学计数法,8e2 = 800

  • 浮点数

  • 复数:虚部以 j 或 J 结尾的为复数

2. 字符串

  • 单引号

  • 双引号

  • 三引号:1.多行注释;2. 实现 多行输出

  • 转义字符:\


    #1.前缀 r
    print(r"\n\r\t")
    #输出 \n\r\t
    #2.前缀 b
    #代表后面的字符串是byte数据。在python2中 print函数操作的字符串全部为byte型数据
       #   python3中 是Unicode数据
    #3.前缀 u
    #代表后面的字符串是Unicode数据。python2为了兼容python3
  • 【**】切片


    str1 = "山西优逸客"
    print(str1[开始下标:结束下标:步进值]
          默认 0    最后    :1
    print(str1[::-1]
  • 字符串的内建函数:
    1. String.capitalize():把字符串的第一个字符大写
    2.String.lower():小写
    3.String.upper():大写
    4.扩充:
    String.center(扩充后的长度,扩充的方式) String在中间,即 在两边填充
    String.ljust(扩充后的长度,扩充的方式) String在左边,即 在右边填充
    String.rjust(扩充后的长度,扩充的方式) String在右边,即 在左边填充
    5.String.count("str",start,end):在start到end之间 str 的次数
    6.String.encode(encoding="utf-8",errors="ignore"):编码 encoding="utf-8"/"gbk"/"gb2312"
    7.String.decode(encoding="utf-8",errors="ignore"[错误 忽略]):解码
    8.String.endswith(”0“):是否是以 0 结尾,填写字符串
    9.String.find(str,start,end):在start到end之前 str 的下标。没有返回-1
    10.String.rfind(str,start,end):在start到end之前 str 的下标
    11.String.index(str,start,end):在start到end之前 str 的下标。没有 报异常
    12.String.isalnum():至少有一个字符,所有字符为数字或字母。为True
    13.String.isalpha():至少有一个字符,所有字符为字母。为True
    14.String.isdecimal():是否字符串都是十进制数字
    15.String.isdigit():是否字符串都是数字
    16.String.islower():是否字符串都是小写
    17.String.isupper():是否字符串都是大写
    18.String.isspace():至少有一个字符,并且String全为空
    19.String.join(seq):将列表对象用String转化为字符串

    arr = ["1","2","3","a","b"]  #必须为字符串才能用 join
    ",".join(arr)
    #输出结果:1,2,3,a,b
    20.String.split(",",num)

    str1 = "1,2,3,4,5,6"
    str1.split(",")   # ["1","2","3","4","5","6"]
    str1.split(",",2)   # ["1","2","3,4,5,6"]
    21.String.splitlines():将字符串通过\n进行分割
    22.String.strip(["srt"]):将字符串前后空格删除,或者删除str

    str2 = "   13   "
    print(len(str2))
    str3 = str2.strip()
    print(len(str3))
    str4 = str3.strip("1")
    print(len(str4))
    str1 = "1_2_3,4,5\n6"
    print(str1.splitlines())

    #输出结果
    9
    2
    1
    ['1_2_3,4,5', '6']

3.列表

  • 列表语法:mylist=[1,2,3,4]

  • 注意:

    1. 列表可以保存任意类型数据

      1. 列表可以使用切片

      2. 列表是可变的,字符串不可变

      3. 可以创建空列表,也可以创建只有一个元素的列表

      4. 可以创建多维列表

  • 列表的遍历 for    item   in   arr:  


    for item in mylist:
       print(mylist.index(item),end=" ")
       print(item)
       
    #
    for i,v in enumerate(mylist):
       print(i)
       print(v)
     
    #enumerate(mylist):将列表转化为(index,item)序列
  • 深拷贝与浅拷贝


    import copy #引入copy包裹

    copy.copy(arr) #浅拷贝 里面变化
    copy.deepcopy(arr) #深拷贝 一直不变
  • 列表内建函数


    List.append() 在最后插入一个元素
    List.insert(10,"a") 在任意位置插入元素
    List.extend([4,5,6]) 合并两个 list 数据
    print(arr + [4,5,6] + [7,8,9]) #合并多个
    List.count(item) 查看某元素在list的次数k
    List.index(item) 查看item在list中的第一个下标。没有 报异常
    List.pop() 删除最后一个元素
    List.remove(item) 删除列表中的元素,有相同的删除第一个
    List.reverse() 将list反转
    List.sort(reverse=True) 排序  默认为升序   reverse=True 降序
    List.copy() 浅拷贝
    List.clear() 清空数组
  • 推倒式(python 特有的写法 语法糖)


    arr1=['1','2','3','4']
    arr2=[item for item in arr1 if item=='3']   #  
    print(arr2)  # ['3']

4.元组

  • mytuple=(1,) 定义一个加,

  • 可以定义空元组 不可以改变

    mytuple=([],[]) 可以改变 可以使用数组的一些方法

  • 注意:

    • 元组元素不可改变

    • 通过圆括号定义

    • 可以使用切片

    • 定义一个元素的元组,逗号不可少

    • 空元组

操作list\tuple的内建函数

  1. len(list)数组的长度

  2. max()数组的最大数

  3. min()数组的最小数

  4. list()将元组转换为列表

  5. tuple()将列表转换为元组

  6. enumerate()返回下标和元素

5.字典

  • 创建方式


    1.json格式创建
    a = {"name":"小白"}
    2.通过内建函数
    b = dict(name="小红",age=10)
    3.通过映射函数的方式
    c = dict(zip(["name","age"],["小红""10"])) #映射函数
    4.可迭代对象的方式
    d = dict([("name","小红"),("age",10)])
  • 如何批量创建:


    mydict = dict.fromkeys(["name1","name2"],"小白")
    print(mydict)
    #输出结果
    #{'name1': '小白', 'name2': '小白'}
  • 字典的访问:mydict[键]

  • 删除:del mydict[键]

  • mydict.clear () 清空

  • mydict.keys () 键名

  • mydict.values () 值

  • mydict.items () 键名:值

  • mydict.setdefault ("键名",值) 添加

  • mydict.pop() 删除

  • mydict.popitem() 删除最后一位的key:value

  • mydict.get("key","info") 存在key,返回key对应的value。不存在key,返回信息 info

数据类型的转化:

  1. float() 转化为浮点型

  2. int() 转化为整型

  3. bin()将十进制转化为 二进制

  4. oct()将十进制转化为 八进制

  5. hex()将十进制转化为 十六进制

集合:

  • 唯一的、不可变的

  1. 创建:


    myset = set([1,2,3])
    myset = set("abc")
  2. 添加:


    myset.add("de")  #{"a","b","c","de"}
    myset.update("de")  #{"a","b","c","d","e"}
  3. 删除:


    myset.remove("d")
  4. 列表去重


    list1 = [1,2,3,4,4,5]
    list2 = list(set(list1));
  5. 差集(-)、交集(&)、并集(|)

运算符:

  1. 算数运算符:

    • 基本算数运算符:+ - * /

      注意:Python3中,除法无论有无复杂类型,结果都精确到 浮点数
      + 操作两个数字型数据 --- 加法
      + 操作一个数字型数据 --- 正数
      + 操作str / list / tuple --- 拼接
      - 和负数 --- 加法运算
      * 操作两个数字型数据 --- 乘法
      *n 操作str / list / tuple --- 重复n次
    • // 除 结果为 int

    • % 取余

    • ** 幂运算

  2. 逻辑运算符

    • and 与

    • or 或

    • not 非

  3. 关系运算符:


    #js     动态类型 弱类型的语言(隐式转换)
    #python 动态类型 强类型的语言(不会转化类型)
    • == 等于

    • !=不等于

    • “> 大于

    • < 小于

    • ">= 大于等于

    • <= 小于等于

  4. 位运算符:

    • &:按位与,两个位 数都为1,按位与结果为1.否则为0;

    • |:按位或,两个位 数只要有一个为1,按位或结果为1.否则为0;

    • ^:按位异或,两个对应的二进位相异时,结果为 1 。相同为 0;

    • ~:按位取反,0为1,1为0;

    • << n:左移n位

    • ''>> n:右移n位

  5. 赋值运算符:

    • =

    • +=

    • -=

    • *=

    • /=

    • %=

    • //=

    • **=

  6. 成员运算符:

    • in


      arr = [1,2,3]
      print(i in arr)  #True
    • not in

  7. 身份运算符:

    • is 判断id地址是否一样,即 为同一个


      num1 = 123;
      num2 = 123;
      print(num1 is num2)  #True
    • is not

运算符优先级:

幂运算、正负、算数运算符、关系运算符、赋值运算符、身份运算符、成员运算符、逻辑运算符

  • ** 指数 (最高优先级) ~ + - 按位翻转, 一元加号和减号 (最后两个的方法名为 +@ 和 -@) */ % // 乘,除,取模和取整除 + - 加法减法 >> << 右移,左移运算符 & 位 'AND' ^ | 位运算符 <= < > >= 比较运算符 <> == != 等于运算符 = %= /= //= -= += *= **= 赋值运算符 is is not 身份运算符 in not in 成员运算符 not and or 逻辑运算符

分支语句:


if 1>2:
   print("1>2")
elif 2==1:
   print("2=1")
else:
   print("1<2")
   

结果1 if 表达式 else 结果2
print(1 if 1>2 else 2)  #输出结果:2

循环语句:

  1. for


    for i in range([start,] end [,step]):
    print(i)


    for i in range(1,10):
       str1 = ""
       for j in range(1,i+1):
           if (j==2 and i==3)or(j==2 and i==4):
               str2 = " "
           else:
               str2 = " "
           str1 += str(j) + "*" + str(i) + "=" + str((i*j)) +str2
       print(str1)

    for i in range(1,10):
       for j in range(1,i+1):
           print("%d*%d=%d"%(j,i,i*j),end=" ")
       print("")
  2. while


    import random
    num = random.randint(0,100)

    s = 0
    while True:
       if s<5:
           num1 = int(input("请输入0-100的数字:"))
           s += 1
           if num1 > num:
               print("大了一点")
           elif num1 < num:
               print("小了一点")
           else:
               print("恭喜你!")
               break

       else:
           print("你输了!")
           break

循环终止语句:

  1. continue:

  2. break:

函数:

  1. 定义:def


    def add(a,b):
       print(a,b)    # 30,20
       return a+b

    print(add(b=20,a=30))  # 50
  • 默认参数:


def add(a=10,b):
print(a,b)    
   return a+b

print(add(b=20))  

 

  • 可变参数:*arr


def aa(*arr):
   print(arr)
aa(1,2,3,4,5)
# 输出结果 (1,2,3,4,5)元组
  • 关键字参数:**attr


def person(name,age=20,**attr):
   print("name:%s"%name)
   print("age:%s"%age)
   print(attr)
 
person(name="xb",age=18,sex="男",tel=123456) #name:xb   age:18     {'sex':'男','tel':123456}
person(name="xb", sex="男", tel=123456) #name:xb   age:20     {'sex':'男','tel':123456}
person("xb", sex="男", tel=123456) #name:xb   age:20     {'sex':'男','tel':123456}
  • 参数的定义顺序:必选参数、默认参数、可变参数、关键字参数


def person(name, age=20,*cj, **attr):
   print("name:%s" % name)
   print("age:%s" % age)
   print(cj)
   print(attr)
person("xb",68,78,84,92, sex="男", tel=123456)
#输出结果:
name:xb
age:68
(78, 84, 92)
{'sex': '男', 'tel': 123456}

返回值:return


yield #将函数的返回内容 装进生成器对象里面
# 求指定数字个数的斐波那契数列
def math4(num1):
   p=0
   q=1
   c=0
   while c<num1:
       yield q
       p,q=q,p+q
       c+=1

print(list(math4(20)))

高阶函数:

  1. 实参高阶函数: 当作形参传入

  2. 返回值高阶函数: 返回值为一个函数


    def add(a,b):
       return a+b
    def sub(a,b):
       return a-b
    def size(a,b,fn):
       return fn(a,b)

    print(size(10,20,add)) #实参高阶函数 30
    print(size(10,20,sub)) #实参高阶函数 -10

    #返回值高阶函数
    def fn():
       def aa():
           print("这是一个函数")
       return aa

    bb = fn()
    bb()

空函数:pass


def fn():
   pass

匿名函数:lambda


lambda 参数 : 函数体(一行)
1.可以有多个参数
2.不需要 return,自动return

调用:
1.自调用
print( (lambda a,b:a+b)(10,20) )    #30
2.字面量
fn = lambda a,b:a+b
print( fn(10,20) )                    #30

常用的使用场合:map、reduce、filter

map(函数,序列)

序列里面的每个都执行函数,返回 map 对象

arr = map(lambda x:x*2,range(1,11))
print(list(arr))
#[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

arr = map(lambda x,y:x+y,range(1,11),range(0,10))
print(list(arr))
#[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]


arr1 = map(lambda x,y:x+y,range(1,11),range(0,5))
print(list(arr1))
#[1, 3, 5, 7, 9]

filter(函数,序列)

筛选符合 函数表达式的,返回 filter 对象

arr = filter(lambda x:x>5,range(1,11))
print(list(arr))
#[6, 7, 8, 9, 10]

reduce(函数,序列)

x指上一次执行的结果,可变的。y指每一次的序列值。返回一个值

import functools
num = functools.reduce(lambda x,y:x+y,range(1,11))

# x:0 y:1
# x:1 y:2
# x:3 y:3
# x:6 y:4

print(num)

作用域:

  • 注意:全局变量 在局部,只能访问,不能 修改

  1. 关键字:global aa #aa 为想要改变的全局变量

     相当于 声明。不能直接 赋值 进行改变
    


  aa = 123
  def fn1():
      global aa,bb
      aa = 456
      bb = 50
     
  fn1()
  print(aa,bb)   # 456
 
  1. 改变全局变量 eg:aa
  2. 声明全局变量 eg:bb
  1. 关键字:nonlocal aa


    num1 = 123
    def fn1():
    num1 = 456
    def fn2():
    nonlocal num1
    num1 += 10
    fn2()
    print(num1)

    fn1()         # 466

闭包函数:

在函数中 可以定义另一个函数时,如果内部函数引用了外部函数的变量,并且调用内部函数,则 产生闭包

作用:

1.在一个函数与一组私有变量之间创建关联关系;

2.在给定函数被多次调用的过程中,这些私有变量保持持久性。



def aa():
   num1 = 456
   def bb():
       print(num1)     # 作用2
   return bb

b = aa()
b()     # 456           # 作用1

递归函数:


def f(num):
   if num==1:
       return 1
   else:
       return f(num - 1)*num

print(f(5))

装饰器:

为了给某程序增添功能

**理解:把需要改变的函数 当作 参数 传入新的函数中,让新的函数完成添加的功能。

	最后 让 原函数名 等于 新函数 的返回值【返回值为一个函数】


  • 三个原则:

    1. 不能修改被装饰的函数的源代码

    2. 不能修改被装饰的函数调用

    3. 满足1、2的情况下给函数添加新功能

  • 装饰器定义公式:

    函数 + 实参高阶函数 + 返回值高阶函数 + 嵌套函数 + 语法糖(@tester)= 装饰器

    import time

    # 装饰器,添加新功能
    def tester(fn):
       def newtest():
           start = time.time()   #记录时间的函数
           fn()                              #不修改被装饰的函数调用
           end = time.time()
           print("总时间:",end-start)
       return newtest

    # 源程序
    def test():
       time.sleep(1)             #程序休眠 1 秒
       print("test is running")
       
    test = tester(test)    # 源程序为“装饰”之后的。名字可以任意
    test()
    @函数名:把后面的 当作参数 传入

    import time

    # 装饰器,添加新功能
    def tester(fn):
       def newtest():
           start = time.time()   #记录时间的函数
           fn()                              #不修改被装饰的函数调用
           end = time.time()
           print("总时间:",end-start)
       return newtest

    @tester
    # 源程序
    def test():
       time.sleep(1)             #程序休眠 1 秒
       print("test is running")

    test()
  • 加入参数:

    按照需求往外加函数

    实质:从里到外 调用


    import time

    装饰器,添加新功能

    def tester1(a,b)

       def tester(fn):

           def newtest():

               start = time.time()   #记录时间的函数

               fn()                              #不修改被装饰的函数调用

               end = time.time()

               print("总时间:",end-start)

               print("参数:",a,b)

           return newtest

       retuen tester

    @tester1(4,5)

    源程序

    def test():

       time.sleep(1)             #程序休眠 1 秒

       print("test is running")

    相当于  test = tester1(4,5)(test)        函数的 柯里化

    test()

文件操作:

读文件:open

open(文件路径,打开文件模式,encoding = "utf-8",errors = "ignore")
#1.读操作
f = open("note.txt","r")  #文件的对象
   con1 = f.read([num]) #num代表读取字符数量,默认为全部
   con2 = f.readline([num]) #文件读取每一行,通过\r \n EOF(文件结束标识)。num代表读取一行的几个字符
   con3 = f.readlines() #返回列表形式
f.close()
print(con) # 山西太原

#2.写操作
f = open("note.txt","w")
   f.write(str)  把str写入文件,不会在str后加入换行符
   f.writelines(arr) 把arr写入
打开文件模式:
r 读操作(默认)  rb 以二进制的方式读取
w 写操作  每次执行重头开始写入,路径不对会创建新文件 【因为 打开 指针指向开始】
a 追加   每次执行直接添加,路径不对会创建新文件【因为 打开 指针指向结尾】
r+ 读写,不创建新文件,每次读写在文件开头
w+ 读写,创建新文件,每次读写会覆盖文件内容
a+ 读写,创建新文件,每次读写追加

f.seek():移动 文件读取指针到指定位置
   f.seek(p,0)  开始,移动到文件第p个字节处,绝对位置
   f.seek(p,1)  当前位置,移动到相对于当前位置之后的p个字节(文件以二进制方式打开)
   f.seek(p,2)  结尾,移动到相对文章尾之后的p个字节(文件以二进制方式打开)
   【p为偏移量】
   
f.tell():返回文件读取指针位置
f.flush():把缓冲区的内容写入硬盘
f.close():1.把缓存区的内容写入硬盘;2.关闭文件

try:
   f = open("note2.txt","r")   #捕获异常。
except:                         #发生异常时执行;
   print("发生错误")
     
   
try:
   f = open("note2.txt","r")   #捕获异常。
finally:                        #无论发不发生异常都执行;
   if f:                       #如果f文件存在
       f.close()               #关闭文件
       
       
       
with open("note2.txt","r") as f: #用完自动关闭文件
   f.read()

pickle:默认存储方式为二进制

  • pickle.dump(obj,f)

  • obj = pickle.load(f)


    import pickle
    # obj = [{"name":"小白","sex":"男","age":20}]
    # with open("note.txt","wb") as f:
    #     pickle.dump(obj,f)
    with open("note.txt","rb") as f:
       obj = pickle.load(f)
       print(obj[0])

csv:存储数据


import csv
with open("demo.csv","w"[,newline=""]) as f:
   writer = csv.writer(f,dialect="excel")
   for i in range(10):
       writer.writerow([1,2,3,4,5])
     
with open("demo.csv","w"[,newline=""]) as f:
   writer = csv.writer(f,dialect="excel")
   writer.writerows([[1,2,3,4,5],[6,7,8]])  #创建多行
   
   writer1 = csv.DictWriter(f,["id","name","sex","tel"])
   writer1.writerheader()

with open("demo.csv","r") as f:
   reader = csv.reader(f)
   print(list(reader))
#
[['1', '2', '3', '4', '5'], [], ['1', '2', '3', '4', '5'], [], ['1', '2', '3', '4', '5'], [], ['1', '2', '3', '4', '5'], [], ['1', '2', '3', '4', '5'], [], ['1', '2', '3', '4', '5'], [], ['1', '2', '3', '4', '5'], [], ['1', '2', '3', '4', '5'], [], ['1', '2', '3', '4', '5'], [], ['1', '2', '3', '4', '5'], []]

with open("demo.csv","r") as f:
   reader = csv.DictReader(f)
   for item in list(reader):
       print(dict(item))
#
{'1': '1', '2': '2', '3': '3', '4': '4', '5': '5'}
{'1': '1', '2': '2', '3': '3', '4': '4', '5': '5'}
{'1': '1', '2': '2', '3': '3', '4': '4', '5': '5'}
{'1': '1', '2': '2', '3': '3', '4': '4', '5': '5'}
{'1': '1', '2': '2', '3': '3', '4': '4', '5': '5'}
{'1': '1', '2': '2', '3': '3', '4': '4', '5': '5'}
{'1': '1', '2': '2', '3': '3', '4': '4', '5': '5'}
{'1': '1', '2': '2', '3': '3', '4': '4', '5': '5'}
{'1': '1', '2': '2', '3': '3', '4': '4', '5': '5'}

写数据:


import csv
#以列表的方式写
with open("demo.csv","w") as f:
   writer = csv.writer(f)
   writer.writerow(["id","name","sex","tel"])
   writer.writerows([
      ["1", "xb", "n", 123456],
      ["1", "xb", "n", 123456],
      ["1", "xb", "n", 123456]
  ])
   
#以字典的方式写
with open("demo.csv","w") as f:
   writer = csv.DictWriter(f,["id","name","sex","tel"])
   writer.writeheader()
   writer.writerow({"id":"1","name":"xb","sex":"n","tel":123456})
   writer.writerows([{"id": "1", "name": "xb", "sex": "n", "tel": 123456},
                    {"id": "1", "name": "xb", "sex": "n", "tel": 123456},
                    {"id": "1", "name": "xb", "sex": "n", "tel": 123456}])

读数据:


import csv
#以列表的方式读
with open("demo.csv","r") as f:
   reader = csv.reader(f)
   print(list(reader))
   
#以字典的方式读
with open("demo.csv","r") as f:
   reader = csv.DictReader(f)
   for item in list(reader):
       print(dict(item))

 

python面向对象:

类和对象:

  • class 类名:

    方法列表

  • 属性 有:

    • 类属性

    • 实例属性 一般写入 def __init__(self): 函数中

  • 方法:

    • 实例的方法

    • 静态方法: 不能调用实例的属性和方法,同时也不能调用类的属性和方法,也不能调用 类的静态方法

    • 类方法:不能调用实例的属性和方法;可以调用类的属性和方法,也可以调用 类的静态方法

  • 实例: 实例可以调用静态方法和类方法!!


class Play:
   name = "xh"   #类属性 静态变量 静态数据
   def __init__(self):  #可以认为 初始函数
       self.name = "xb" #实例属性
       
#实例的方法
   def type(self):           #若方法中没有用到属性,self可以不填
       print("1")
#实例的方法
   def nl(self):         #最好 填入 self
       print("2")
       
#静态方法:
@staticmethod
def say():
       print("3")
       
   #类方法:
   @classmethod
   def say1(cls):
       print("4")
       
   #类方法:
   @classmethod
   def say2(cls):
       print(cls.name)
       cls.say2()
       cls.say()
       
p1 = Play()   #p1 实例

print(Car.__name__)   # 类名
print(Car.__doc__)    # 对类的描述 注释
print(Car.__bases__)  # 所有的父类,返回 元组
print(Car.__base__)   # 父类
print(Car.__dict__)   # 返回所有的方法,以字典的形式
print(Car.__module__) # 返回类所在的模块 __mainj__
print(Car.__class__)  # 类对应的类 <class 'type'>

特殊实例的方法:(魔法方法)


# __new__(cls)
__new__至少有一个参数cls,代表要实例化的类。

class car:
   def __new__(cls):                 # 实例化对象的过程
       return object.__new__(cls)    # 返回实例
   def __init__(self):
       self.pp = "大众"
   def run(self):
       print("运行")

# __init__(self):   # 初始化实例

# __str__(self):   # 给实例一个描述
class car:
   def __init__(self):
       self.pp = "大众"
   def run(self):
       print("运行")
   def __str__(self):
       return "这是一个汽车实例"
   
c = car()
print(c)   # 触发 __str__   即 输出 "这是一个汽车实例"
    1. 作用同上


# __repr__(self):   # 给实例一个描述
class car:
   def __init__(self):
       self.pp = "大众"
   def run(self):
       print("运行")
   def __repr__(self):
       return "这是一个汽车实例"
   
c = car()
print(c)   # 触发 __repr__   即 输出 "这是一个汽车实例"

# __del__(self):   # 实例被注销时调用
class car:
   def __init__(self):
       self.pp = "大众"
   def run(self):
       print("运行")
   def __del__(self):
       print("这是一个汽车实例")
   
c = car()
c2 = car()
del c   # 触发 __del__   即 输出 "这是一个汽车实例"
del c2  # 触发 __del__   即 输出 "这是一个汽车实例"

 

继承和派生:

继承:

目的:延续旧的类的功能

  • 基类(base class)

  • 超类(super class)

  • 父类(father class)


    class B:
      name1 = "xh"
      def __init__(self):
          self.name = "xb"
      def say(self):
          print("1")
      @staticmethod
      def say1():
          print("2")
      @classmethod
      def say2(cls):
          print("3")
       
    class A(B):              #继承 一个
         pass

     a = A()
     a.say()
     a.say1()
     a.say2()
     print(a.name)
     print(a.name1)

class B: name1 = "xh" class C: name1 = "xb" class A(B,C): #继承 多个 pass

a = A() print(a.name1) # xh

  ```python
  class D:
      name1 = "D"
  class B(D):
      name = "B"
  class C:
      name1 = "C"
  class A(B,C):
      pass
  a = A()
  print(a.name1)        #D   就近原则,深度优先


 

派生:

目的:延续旧的类的功能并添加新的功能

  • 派生类(derived class)

  • 子类(child class)


    class B:
       name1 = "xh"
       def __init__(self):
           self.name = "xb"
       def say(self):
           print("1")
       @staticmethod
       def say1():
           print("2")
       @classmethod
       def say2(cls):
           print("3")
           
    class A(B):              #继承
       name1 = "小红"
    def __init__(self):
           self.name = "小白"
    a = A()
    print(a.name)           #小白
    print(a.name1)          #小红

    class myfloat(float):
       def __new__(cls,var):
           return float.__new__(cls,round(var,3))
    num = myfloat(4.1213)
    print(num)                      #4.121
    num1 = myfloat(4.1003)
    print(num1)                      #4.1
    num2 = myfloat(4)
    print(num2)                      #4.0



    class myfloat(float):
       def __new__(cls,var):
           return float.__new__(cls,round(var,2))
       def __init__(self,con):
           self.num = con
       def get(self,type):
           return ("%0.2f%s"%(self.num,type))
    num = myfloat(4.1213)
    print(num.get("$"))
    print(num.get("¥"))

     

 

 

面向对象中常用的内建函数:

  • issubclass(sub,parent) 判断sub是否为parent的子类 返回bool

  • isinstance(ins,class) 判断ins是否为class的实例 返回bool

  • hasattr(obj,"attr") 判断obj中是否有attr属性

  • getattr(obj,"attr") 获取obj中attr属性

  • setattr(obj,"attr") 设置obj中attr属性

  • delattr(obj,"attr") 删除obj中attr属性

  • dir() 列出类或实例的属性和方法 以列表的形式

  • super() 寻找父类信息super(type[,object-or-type])


    class B:
       def __init__(self,val1,val2):
           self.val1 = val1
           self.val2 = val2
    class A(B):
       def __init__(self,val1,val2):
           super().__init__(val1,val2)
  • vars(object) 返回对象object的属性 以字典的形式

私有:


class A:
   def __say(self):
       print("这是A")
   def __init__(self):
       self.__name = "aa"

a = A()
a.__say()
print(a.__name)

# 报错
a.__say()
AttributeError: 'A' object has no attribute '__say'

class A:
   def __say(self):
       print("这是A")
   def __init__(self):
       self.__name = "aa"

a = A()
print(dir(a))
a._A__name = "bb"
print(a._A__name)

#
['_A__name', '_A__say', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
bb
继承:

class A:
   def __say(self):
       print("这是A")
   def __init__(self):
       self.__name = "aa"
class B(A):
   pass
b = B()
print(dir(b))
b._A__name = "bb"
print(b._A__name)
b._A__say()

#
['_A__name', '_A__say', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
bb
这是A

单例模式:


class Person:  
   __instance = None
   def __new__(cls):
       if cls.__instance == None:
           cls.__instance = object.__new__(cls)
       return cls.__instance
   def __init__(self):
       pass
   def say(self):
       print(self.name)

p = Person()  
p.name = "小艾"  
p1 = Person()  
p1.say()      
             
#小艾

工厂模式:


class Dz:
   def __init__(self):
       self.type = "大众"
   def run(self):
       print("启动")
   def stop(self):
       print("熄火")

class BMW:
   def __init__(self):
       self.type = "宝马"
   def run(self):
       print("启动")
   def stop(self):
       print("熄火")
       
class Carfactory:
   def CreateCar(self,type):
       if type == "dz":
           obj = Dz()
       elif type == "BMW":
           obj = BMW()
       return obj
   
cf = Carfactory()

car1 = cf.CreateCar("dz")
print(car1.type)
car1.run()
car1.stop()

car2 = cf.CreateCar("BMW")
print(car2.type)
car2.run()
car2.stop()

封装:

对内部数据进行保护(隐藏),或合理的暴露

异常:

即便Python程序的语法是正确的,在运行它的时候,也有可能发生错误。运行期检测到的错误被称为异常。

异常类:


BaseException
+-- SystemExit  解释器请求退出
+-- KeyboardInterrupt  用户中断执行(ctr + c)
+-- GeneratorExit   生成器发生异常来通知退出
+-- Exception   常规错误基类
     +-- StopIteration 迭代器没有更多的值
     +-- StopAsyncIteration
     +-- ArithmeticError   数值计算错误基类
     |    +-- FloatingPointError   浮点计算错误
     |    +-- OverflowError    数值运算超出最大限制
     |    +-- ZeroDivisionError    除(或取模)零 (所有数据类型)
     +-- AssertionError    断言语句失败
     +-- AttributeError    对象没有这个属性
     +-- BufferError  
     +-- EOFError  没有内建输入,到达EOF标记
     +-- ImportError   导入模块失败
     |    +-- ModuleNotFoundError
     +-- LookupError   无效数据查询基类
     |    +-- IndexError 序列中没有此索引(index)
     |    +-- KeyError 映射中没有这个键
     +-- MemoryError   内存溢出错误
     +-- NameError 未声明未初始化的本地变量
     |    +-- UnboundLocalError 访问未初始化的本地变量
     +-- OSError   操作系统错误
     |    +-- BlockingIOError 操作阻塞设置为非阻塞操作的对象(例如套接字)时引发
     |    +-- ChildProcessError 子进程上的操作失败时引发
     |    +-- ConnectionError 连接相关的问题的基类
     |    |    +-- BrokenPipeError
     |    |    +-- ConnectionAbortedError
     |    |    +-- ConnectionRefusedError
     |    |    +-- ConnectionResetError
     |    +-- FileExistsError 尝试创建已存在的文件或目录时引发
     |    +-- FileNotFoundError    在请求文件或目录但不存在时引发
     |    +-- InterruptedError 系统调用被输入信号中断时触发
     |    +-- IsADirectoryError 在目录上请求文件操作时引发
     |    +-- NotADirectoryError 在对非目录的os.listdir()事物请求目录操作(例如)时引发
     |    +-- PermissionError 尝试在没有足够访问权限的情况下运行操作时引发 - 例如文件系统权限。
     |    +-- ProcessLookupError 当给定进程不存在时引发
     |    +-- TimeoutError 系统功能在系统级别超时时触发。
     +-- ReferenceError    弱引用(Weak reference)试图访问已经垃圾回收了的对象
     +-- RuntimeError  一般的运行时错误
     |    +-- NotImplementedError 尚未实现的方法
     |    +-- RecursionError
     +-- SyntaxError 一般的解释器系统错误
     |    +-- IndentationError 缩进错误
     |         +-- TabError    Tab 和空格混用
     +-- SystemError Python 语法错误
     +-- TypeError     对类型无效的操作
     +-- ValueError    传入无效的参数
     |    +-- UnicodeError  Unicode 相关的错误
     |         +-- UnicodeDecodeError Unicode 解码时的错误
     |         +-- UnicodeEncodeError  Unicode 编码时错误
     |         +-- UnicodeTranslateError   Unicode 转换时错误
     +-- Warning   警告的基类
          +-- DeprecationWarning   关于被弃用的特征的警告
          +-- PendingDeprecationWarning    关于特性将会被废弃的警告
          +-- RuntimeWarning   可疑的运行时行为(runtime behavior)的警告
          +-- SyntaxWarning    可疑的语法的警告    
          +-- UserWarning  用户代码生成的警告
          +-- FutureWarning    关于构造将来语义会有改变的警告
          +-- ImportWarning
          +-- UnicodeWarning
          +-- BytesWarning
          +-- ResourceWarning

异常处理:


try: # 捕获异常
   num=int(input('请输入数字:'))
   print(num) # 没有异常执行
except: #出现错误时执行
   print('输入错误!')

finally:

无论是否发生异常finally都会执行


try:
   num=int(input('请输入数字:'))
   print(num)
finally:
   print('错误!')

else:

没有异常时执行


try:
   num=int(input('请输入数字:'))
   print(num)
except:
   print('输入错误!')
else:
   print('正确!')

except:

except后面可以写异常名称,当出现异常的名称与写入的异常名称相同时,执行语句。不写入异常名称时,当作通配符,处理所有异常


try:
   num=1/0
   print(num) #该异常的类为ZeroDivisionError
except ValueError:
   print('输入错误!')
   
'''
异常类不匹配,异常结果为
Traceback (most recent call last):
File "c:/Users/JPC/Desktop/py/面向对象/deom4.py", line 2, in <module>
  num=1/0
ZeroDivisionError: division by zero
'''

异常的传递:


def A():
   num=1/0
   print(num)

def B():
   return A()
   
def C():
   return B()

try:
   C()
except:
   print('错误!')

异常抛出: raise


def input_password():

   # 1. 提示用户输入密码
   pwd = input("请输入密码:")

   # 2. 判断密码长度,如果长度 >= 8,返回用户输入的密码
   if len(pwd) >= 8:
       return pwd

   # 3. 密码长度不够,需要抛出异常
   # 1> 创建异常对象 - 使用异常的错误信息字符串作为参数
   ex = Exception("密码长度不够")

   # 2> 抛出异常对象
   raise ex

-=
try:
   user_pwd = input_password()
   print(user_pwd)
except Exception as result:
   print("发现错误:%s" % result)

自定义异常:引入Exception类


class MyException(Exception):
   pass

try:
   phone_num = input("请输入手机号:")

   if phone_num.isdecimal() is False:
       #print("手机号码含非数字")
       raise MyException("手机号码含非数字")
   elif len(phone_num) != 11:
       # print("手机号长度不够")
       raise MyException("手机号长度不够")
except MyException as error:
   print("提示:%s" % error)


结果:
请输入手机号:sgvsdfgsgsgsdgds
提示:手机号码含非数字
class MyException(Exception):
   pass

try:
   phone_num = input("请输入手机号:")

   if phone_num.isdecimal() is False:
       # print("手机号码含非数字")
       raise MyException()
   elif len(phone_num) != 11:
       # print("手机号长度不够")
       raise MyException()
except MyException:
   print("错误")
   
结果:
#
请输入手机号:asad
错误
#
请输入手机号:123456
错误

包、模块:

  • bao1文件夹作为包 必须含有 __init__.py文件

1. 构建模块的层级包

2. 控制模块全部导出 *

3. 使用相对路径导入包中子模块


# 1
import a,b          引入同级的.py文件
from bao1 import a,b      引入bao1文件夹中的a.py,b.py文件
bao1文件夹作为包 必须含有 __init__.py文件
from bao1 import a as a2  相当于给bao1中的a起名字为a2
from bao1.a import aa2,aa3  只引入bao1中a.py文件中的 aa2、aa3方法

# 2
from bao1.a import *     引入bao1中a.py文件中的所有命名
* 默认为所有的   也可在bao1中a.py文件中 通过 __all__=["aa3"] 指定 * 导出内容

# 3
相对路径的方式:【.代表当前包,..代表上一级的包】
1.使用 . 的模式 不是包的目录中 导入 会引发错误【.只能在包之间用】
2.from .a import aa       引入当前包中a.py文件中的 aa方法
3.使用 . 模式的文件 不能被当做主程序 运行,只能 主程序 引入该文件才能使用

4. 将模块分割成多个文件:

 

 

5. 利用命名空间导入目录分散的代码:

每个部分被组织为 文件 目录

 

6. 重新加载模块:

  • import imp

  • imp.reload(模块) 【改变模块内容的值,主函数中也改变】

 

 

 

 

 

 

 

 

7. 运行 目录或压缩文件:

 

8. 读取位于包中的数据文件:


  • 假设 mypackage :
       __init__.py
       somedata.dat
       spam.py
       
    # 若 spam.py 文件需要读取 somedata.dat 文件内容

    #在spam.py中:

    import pkgutil
    data = pkgutil.get_data(__package__,"somedata.dat")

9. 通过字符串名导入模块:

  • import importlib

  • aa = importlib.import_module("mypackage.aa")

  • print(aa.data)

协程,进程,线程


并行:同时能够做多少事
并发量:同一时间所能够容纳任务的极限

处理并发:
进程处理:同时开始多个进程完成轮循(很少用)
线程处理:一个进程的多个线程中,完成轮循(python为假线程 并行是假的)
协程处理:一个线程中完成轮循(耗费资源最少)

机器学习


numpy:查看矩阵

 

python GUI:

简称 C/S 结构,是一种网络架构

tkinter编程:

  1. 步骤

    • 导入tkinter模块

    • 创建顶层

  2. 窗口控件

    • 弹框:


      import tkinter as tk
      from tkinter import messagebox

      window = tk.Tk()
      window.title("我的窗口")
      window.geometry("600x400")

      def fn():
         tk.messagebox.showerror(title="error",message="代码出现错误")
         # tk.messagebox.showeinfo(title="info",message="您选择了科学型计算机")
         # tk.messagebox.showwarning(title="warning",message="这是一个警告")
         
         # b = tk.messagebox.askyesno(title="ask",message="确定关闭吗?") # True / False
         # b = tk.messagebox.askokcancel(title="ask",message="确定还是取消?") # True / False
         # b = tk.messagebox.askquestion(title="ask",message="是否关闭?") # yes / no
         # b = tk.messagebox.askretrycancel(title="ask",message="程序未响应,是否退出?")
         # # True / False
         # b = tk.messagebox.askyesnocancel(title="ask",message="是否退出?")#True/False/None
      button = tk.Button(window,text = "chick",command = fn)

  import tkinter as tk
 
  window = tk.Tk()  #创建窗口
  window.title("我的窗口")  #设置窗口的 title
  window.geometry("600x400")  #设置窗口大小
  window.resizable(0,0)  #重置尺寸的范围 (0,0)代表不能拖拽
 
  #控件:
  # 1.Labei 标签(放文字)
  str1 = tk.StringVar()
  str1.set("hello world")
  img1 = tk.PhotoImage(file = "4a43.png")  #只能 .png 或 .gif
  #,image = img1
  l1 = tk.Label(window)  # 实例化 Label 第一个参数 为主窗口
  l1["text"] = "hello world"   # 文本 内容
  l1["font"] = ("",20,"bold italic")
  l1["bg"] = "#ff6700"   #背景色
  l1["fg"] = "#fff"   #前景色
  l1["width"] = 20
  l1["height"] = 2
  l1["anchor"] = "c"    #文本位置   "n"北:上 "s"南:下   "w"西:左 "e"东:右 ne nw se sw c:中间
  # l1["image"] = img1
  # l1["varlable"] = str1 # 可变量 等于 一个变量,必须用tk.StringVar()定义,用set设置
 
  # 2.Button 按钮
  num = 0
  def aa():
      # print(123)
      global num
      num += 1
      l1["text"] = "hello world"+str(num)
  b1 = tk.Button(window,text = "点击",command = aa)
  b1["width"] = 20
  b1["height"] = 1
  b1["bg"] = "#333"
  b1["fg"] = "#fff"
 
  l1.pack()
  b1.pack()
  window.mainloop() #进行事件循环

  import tkinter as tk
 
  window = tk.Tk()  #创建窗口
  window.title("我的窗口")  #设置窗口的 title
  window.geometry("600x400")  #设置窗口大小
  window.resizable(0,0)  #重置尺寸的范围 (0,0)代表不能拖拽
 
  # 3.输入组件:
  e = tk.Entry(window)
  e["selectbackground"] = "red"  #选中文字,的背景色
  e["selectforeground"] = "blue" #选中文字,的颜色
  # e["show"] = "*"   #呈现的样式
 
  # 4.文本域组件
  t = tk.Text(window)
 
  def fn():
      val = e.get()    #get()获取 e 中的值
      t.insert("end",val)   #在 t 中插入
 
  btn1 = tk.Button(window,text = "after",command = fn)
 
  def fn1():
      val = e.get()    #get()获取 e 中的值
      t.insert("insert",val)   #在 t 中插入
 
  btn2 = tk.Button(window,text = "insert",command = fn1)
 
  e.pack()
  btn1.pack()
  btn2.pack()
  t.pack()
  window.mainloop() #进行事件循环

  import tkinter as tk
 
  window = tk.Tk()  #创建窗口
  window.title("我的窗口")  #设置窗口的 title
  window.geometry("600x400")  #设置窗口大小
  window.resizable(0,0)  #重置尺寸的范围 (0,0)代表不能拖拽
 
  l1 = tk.Label(window,text = "B",width = 20,height = 3,bg = "#333",fg = "#fff",font = ("",20))
 
  v1 = tk.Variable()
  v1.set("B")
  def fn1():
      l1["text"] = v1.get()
  # 5.单选
  r1 = tk.Radiobutton(window,text = "A",variable= v1,value = "A",command = fn1)
  r2 = tk.Radiobutton(window,text = "B",variable= v1,value = "B",command = fn1)
  r3 = tk.Radiobutton(window,text = "C",variable= v1,value = "C",command = fn1)
  r4 = tk.Radiobutton(window,text = "D",variable= v1,value = "D",command = fn1)
 
  l1.pack()
  r1.pack()
  r2.pack()
  r3.pack()
  r4.pack()
  window.mainloop() #进行事件循环

  import tkinter as tk
 
  window = tk.Tk()  #创建窗口
  window.title("我的窗口")  #设置窗口的 title
  window.geometry("400x400")  #设置窗口大小
  # window.resizable(0,0) #重置尺寸的范围 (0,0)代表不能拖拽
 
  l1=tk.Label(window,text="用户名:",bg="#000",fg="#fff",font=("",10))
  l1.place(x=40,y=40)
 
  username,password=False,False
 
  def fn1():
      global username
      con = e.get()
      if len(con)>=10:
          # print(con)
          l3["text"] = "用户名正确"
          l3["fg"] = "green"
          username = True
          isLogin(username,password)
          return True
      else:
          return False
  def fn2():
      l3["text"]="用户名不正确"
      l3["fg"]="red"
 
  e = tk.Entry(window,validate="focusout",validatecommand=fn1,invalidcommand=fn2)
  # validate     focus   focusin   focusout   key
  e.place(x=100,y=40)
 
  l3=tk.Label(window,text="",font=("",10))
  l3.place(x=280,y=40)
 
  l2=tk.Label(window,text="密码:",bg="#000",fg="#fff",font=("",10))
  l2.place(x=40,y=80)
 
 
  def fn3():
      global password
      con = e1.get()
      if len(con)>=6:
          # print(con)
          l4["text"]="密码正确"
          l4["fg"] = "green"
          password = True
          isLogin(username,password)
          return True
      else:
          return False
  def fn4():
      l4["text"]="密码不正确"
      l4["fg"] = "red"
      pass
  e1 = tk.Entry(window,validate="focusout",validatecommand=fn3,invalidcommand=fn4)
  e1.place(x=100,y=80)
 
  l4=tk.Label(window,text="",font=("",10))
  l4.place(x=280,y=80)
 
  def isLogin(u,p):
      if u and p:
          btn1["state"]="normal"
      else:
          btn1["state"]="disable"
  def isOK():
      u = e.get()
      p = e1.get()
      if u == "1234567890" and p == "123456":
          tk.Label(window,text="登录成功").place(x=100,y=160)
      else:
          tk.Label(window, text="登录失败").place(x=100, y=160)
          btn1["state"]="disable"
          e["text"]=""
          e1["text"]=""
  btn1 = tk.Button(window,text="登录",command=isOK)
  btn1.place(x=100,y=120)
  btn1["state"]="disable"
  btn1["activebackground"]="blue"
  btn1["activeforeground"]="#fff"
 
  btn2 = tk.Button(window,text="注册")
  btn2.place(x=200,y=120)
  btn2["state"]="normal"
  btn2["activebackground"]="blue"
  btn2["activeforeground"]="#fff"
 
  window.mainloop() #进行事件循环

  import tkinter as tk
 
  window = tk.Tk()  #创建窗口
  window.title("我的窗口")  #设置窗口的 title
  window.geometry("400x400")  #设置窗口大小
  # window.resizable(0,0) #重置尺寸的范围 (0,0)代表不能拖拽
 
  l = tk.Label(window,width = 10,height = 1,bg = "#333",fg = "#fff")
  l.pack()
  e = tk.Entry(window)
  e.pack()
  def fn():
      arr = lx.curselection()  #选中数据的下标,返回一个元组
      con = e.get()
      if len(con) == 0:
          return
      if len(arr) == 0:
          lx.insert("end",con)
      elif len(arr) == 1:
          lx.insert(arr[0]+1,con)
      else:
          num = 1
          for i in arr:
              lx.insert(i+num,con)
              num += 1
  btn = tk.Button(window,text = "插入",command = fn)
  btn.pack()
  # 6.下拉列表
  lx = tk.Listbox(window,selectmode = "extended") #全选
  lx.insert(0,"北京")
  for item in ["上海","广州","深圳"]:
      lx.insert("end",item)
  lx.pack()
 
  def fn1():
      print(lx.curselection())
  btn2 = tk.Button(window,text = "点击",command = fn1)
  btn2.pack()
 
  window.mainloop() #进行事件循环

  import tkinter as tk
 
  window = tk.Tk()  #创建窗口
  window.title("我的窗口")  #设置窗口的 title
  window.geometry("400x400")  #设置窗口大小
  # window.resizable(0,0) #重置尺寸的范围 (0,0)代表不能拖拽
 
  v1 = tk.Variable()
  v1.set(1)
  v2 = tk.Variable()
  v2.set(1)
  def fn():
      con1 = int(v1.get())
      con2 = int(v2.get())
      if con1==1 and con2!=1:
          l["text"]="我喜欢看电影"
      elif con1==0 and con2==1:
          l["text"] = "我喜欢敲代码"
      elif con1==1 and con2==1:
          l.config(text = "都喜欢")
      else:
          l.config(text = "都不喜欢")
      print(con1,con2)
  l = tk.Label(window,width = 20,height = 3,bg = "#333",fg = "#fff",font = ("",24))
  l.pack()
  # 7.复选框
  c1 = tk.Checkbutton(window,text = "看电影",variable = v1,command=fn)
  c1.pack()
  c2 = tk.Checkbutton(window,text = "敲代码",variable = v2,command=fn)
  c2.pack()
 
  window.mainloop() #进行事件循环

  import tkinter as tk
  from tkinter import ttk
 
  window = tk.Tk()
  window.geometry("600x300")
  window.resizable(0,0)
 
  l1 = tk.Label(window)
  l1.config({
      "text":"150.0",
      "fg":"#fff",
      "bg":"#000",
      "font":("",20,"italic bold")
 
  })
 
  l1.pack()
 
  def fn1(v):   #必须传参数
      l1["text"] = v
  # 8.Scale 滑块
  s1 = tk.Scale(window,command = fn1)
  s1.config({
      "orient":tk.HORIZONTAL,  # 水平方向
      "from_":50,
      "to":200,
      "length":200,
      "resolution":1,  # 步进值(默认为 1)
      "digits":3,  # 显示数字位数(默认 正常)
      "tickinterval":50,  # 间隔刻度(默认 没有)最小设置为 步进值的一半
      "showvalue": 1, # 布尔值 1(显示上方的值) / 0(不显示)
      "label":"温度",  # 给滑块添加标签
  })
  s1.set(150) # 设置值
  print(s1.get()) # 获取
 
  s1.pack()
 
  window.mainloop()

  import tkinter as tk
  from tkinter import ttk
 
  window = tk.Tk()
  window.geometry("600x300")
  window.resizable(0,0)
 
  def fn2():
      con = e.get()
      if int(con)>=0 and int(con)<=100:
          s1["value"] = con
          s2.set(con)
  def fn3():
      print("输入错误")
  l1 = tk.Label(window,text = "0")
  l1.pack()
 
  def fn():
      con = s1.get()
      s2.set(con)
      l1["text"] = con
  # 9.数字框
  s1 = tk.Spinbox(window)
  # s1["values"] = ("北京","上海","广州")
  # 不能设置默认值 set( )
  s1.config({
      "from_":0,
      "to":100,
      "width":10,
      "command":fn
  })
  s1.pack()
 
  def fn1(v):
      s1["value"] = v
      l1["text"] = v
      s1["value"] =""
 
  s2 = tk.Scale(window)
  s2.config({
      "orient":tk.HORIZONTAL,
      "from_":0,
      "to":100,
      "length":200,
      "command":fn1
  })
  s2.pack()
  window.mainloop()

  import tkinter as tk
  from tkinter import ttk
 
  window = tk.Tk()
  window.geometry("600x600")
  window.resizable(0,0)
 
  # 10.canvas
  canvas = tk.Canvas(window)
  canvas.config({
      "width":500,
      "height":500,
      "bg":"#ccc"
  })
  canvas.pack()
 
  # 画图片
  img1 = tk.PhotoImage(file = "4a43.png",width = 200,height = 100)
  cimg = canvas.create_image(100,100,image = img1)
  cline = canvas.create_line(0,0,200,200,fill = "red")
  carc = canvas.create_arc(200,200,300,300,extent = 270,start = 90,fill = "blue")
  #extent旋转的角度 start开始的角度 fill 填充的颜色
  coval = canvas.create_oval(300,300,350,350,fill = "yellow")
  ctext = canvas.create_text(400,100,text = "Python",font = ("",20))
  cp = canvas.create_polygon(0,0,0,100,100,100,fill = "blue")
  cr = canvas.create_rectangle(400,100,500,200)
 
  def fn():
      canvas.move(coval,-20,-20)
  btn = tk.Button(window,text = "点击",command = fn)
  btn.pack()
 
  window.mainloop()

  import tkinter as tk
  from tkinter import ttk
 
  window = tk.Tk()
  window.geometry("600x600")
  window.resizable(0,0)
 
  # 菜单栏
  # 11.Menu
 
  menu1 = tk.Menu(menubar,tearoff = 0) # 创建菜单项 tearoff = 0 / False 表示 不能移出
  menu1.add_command(label = "New Project...") # 添加内容
  menu1.add_command(label = "New...")
  menu1.add_command(label = "New Scratch File")
  menu1.add_command(label = "Open...")
  menu1.add_command(label = "Open URL...")
  menu1.add_command(label = "Save As...")
  menu1_1 = tk.Menu(menu1,tearoff = 0)
  menu1_1.add_command(label = "练习")
  menu1_1.add_command(label = "geting")
  menu1_1.add_command(label = "python例题")
  menu1_1.add_command(label = "demo1")
  menu1_1.add_command(label = "demo")
  menu1.add_cascade(label = "Open Recent",menu = menu1_1)
  menu1.add_command(label = "Close Project")
  menu1.add_command(label = "Rename Project...")
  menu1.add_separator()
 
 
  menu1_2 = tk.Menu(menu1,tearoff = 0) # 创建菜单项 tearoff = 0 / False 表示 不能移出
  img1 = tk.PhotoImage(file = "2.png",width=20,height=10)
  menu1_2.add_command(label = "设置",image = img1,compound = "left")
  menu1.add_cascade(label = "首选项",menu = menu1_2)
  menubar.add_cascade(label = "File",menu = menu1)
 
  yuyan = tk.Variable()
  yuyan.set(1)
  def fn1():
      print(yuyan.get())
  # 语言选项
  menu1_3 = tk.Menu(menu1,tearoff = False)
  menu1.add_cascade(label = "选择语言",menu = menu1_3)
  menu1_3.add_radiobutton(label = "英语",variable = yuyan,value = 0,command = fn1)
  menu1_3.add_radiobutton(label = "汉语",variable = yuyan,value = 1,command = fn1)
  menu1_3.add_radiobutton(label = "德语",variable = yuyan,value = 2,command = fn1)
 
  s1 = tk.Variable()
  s1.set(1)
  s2 = tk.Variable()
  s2.set(0)
  s3 = tk.Variable()
  s3.set(0)
 
  def fn2():
      print(s1.get())
      print(s2.get())
      print(s3.get())
  menu1_4 = tk.Menu(menu1,tearoff = False)
  menu1.add_cascade(label = "字体",menu = menu1_4)
  menu1_4.add_checkbutton(label = "加粗",variable = s1,command = fn2)
  menu1_4.add_checkbutton(label = "倾斜",variable = s2,command = fn2)
  menu1_4.add_checkbutton(label = "下划线",variable = s3,command = fn2)
 
  window.configure(menu = menubar) # 添加菜单栏
 
  window.mainloop()

  import tkinter as tk
  from tkinter import ttk
 
  window = tk.Tk()
  window.geometry("600x600")
  window.resizable(0,0)
 
  # menubar = tk.Menu(window,tearoff = False)
  # for item in ["css","html","javascript","python"]:
  #     menubar.add_command(label = item)
  #
  # def chilk(e):
  #     menubar.post(e.x_root,e.y_root)
  # window.bind("<Button-3>",chilk)
 
  # 12. Frame
  f1 = tk.Frame(window,width = 200,height = 200,bg = "red")
  f1.pack()
  f2 = tk.Frame(f1,width = 100,height = 100,bg = "blue")
  f2.pack()
  window.mainloop(
  1. 事件驱动处理

  2. 布局管理器

    • pack 相对布局:组件的大小和位置会随着窗口的大小而改变


      l1 = tk.Label(window)  # 实例化 Label 第一个参数 为主窗口
      l1["text"] = "hello world"   # 文本 内容
      l1["font"] = ("",20,"bold italic")  
      l1["bg"] = "#ff6700"   #背景色
      l1["fg"] = "#fff"   #前景色
      l1["width"] = 20
      l1["height"] = 2
      l1["anchor"] = "n"  #文本位置 "n"北:上 "s"南:下   "w"西:左 "e"东:右 ne nw se sw c:中间

      l1.pack()

      # 或者
      l1 = tk.Label(window,text = "hello world",font = ("",20,"bold italic"))

      #font =()元组设置字体, “字体 用英文”,字体大小,字体样式(加粗、倾斜)
      l1.pack()

      l1.pack(anchor = "ne")  # 锚位置 当剩余空间远远大于所需空间时
      l1.pack(side = "top") # 位置(对齐方式)
      #side: 'top' / 'left' / 'right' / 'bottom'
      # tk.TOP / tk.LEFT / tk.RIGHT / tk.BOTTOM
      l1.pack(fill = tk.X)  # 位置的填充
      #fill: tk.X / tk.Y / 'x' / 'y'
      l1.pack(expand = 1) # 扩充 / 展开
      # expand: 0 (默认,不扩展) / 1(扩展,即 占剩余空间)
      l1.pack(padx = 10,pady = 10)
      # padx / pady : 外间距
      # ipadx / ipady : 内间距
      b2.pack_forget() # 隐藏,相当于 display:none
    • place 绝对布局:组件的大小和位置不会随着窗口的大小而改变


      .place(x=120,y=120)
      # x / y   # 相对于父元素 x轴偏移量 / y轴偏移量
      # relx / rely (0~1) # 参照于父元素 width,height
      # width / height
      # relwidth / relheight (0~1) # 参照于父元素 width,height
      b2.place_forget() # 隐藏,相当于 display:none
    • grid 网格布局:通过表格形式进行布局


      b1.grid(row = 0,column = 0,padx = 10,pady = 10)
      # row 行
      # columnspan 占的列数
      # rowspan 占的行数
      #sticky 相对于表格的对齐方式 n s e w 4个方位
  3. 事件的循环

    • 鼠标事件


      import tkinter as tk

      window = tk.Tk()  #创建窗口
      window.title("我的窗口")  #设置窗口的 title
      window.geometry("600x400")  #设置窗口大小

      # 鼠标事件
      window.bind("<Button-1>",lambda x:print("左击"))
      window.bind("<Button-2>",lambda x:print("中间键"))
      window.bind("<Button-3>",lambda x:print("右击"))
      window.bind("<Button-4>",lambda x:print("滚轮向上"))
      window.bind("<Button-5>",lambda x:print("滚轮向下"))

      window.bind("<Double-Button-1>",lambda x:print("左键双击"))
      window.bind("<Double-Button-2>",lambda x:print("中间键双击"))
      window.bind("<Double-Button-3>",lambda x:print("右键双击"))

      window.bind("<Triple-Button-1>",lambda x:print("左键三击"))
      window.bind("<Triple-Button-2>",lambda x:print("中间键三击"))
      window.bind("<Triple-Button-3>",lambda x:print("右键三击"))

      window.bind("<B1-Motion>",lambda x:print("左键按下移动"))
      # ...
      window.bind("<ButtonRelease-1>",lambda x:print("左键抬起"))
      # ...
      window.bind("<Enter>",lambda x:print("鼠标移入"))
      window.bind("<Leave>",lambda x:print("鼠标移出"))

      window.mainloop() #进行事件循环
    • 键盘事件

posted @ 2019-03-07 17:51  我们如此闪耀  阅读(629)  评论(0编辑  收藏  举报