os
import os
#通过os.system()调用
# os.system("notepad.exe")
# os.system("ping www.baidu.com")
# os.system("cmd")
#直接调用可执行的文件
os.startfile(r"C:\Program Files (x86)\WXWork\WXWork.exe")
#coding=utf-8
#测试os模块中,关于文件和目录的操作
import os
#################获取文件和文件夹的信息##########################
# print(os.name) #windows --> nt linux和unix --> posix(操作系统的名字)
# print(os.sep) # \ /
# print(repr(os.linesep)) # \r\n \n\
print(os.stat("my02.py"))
################关于工作目录的操作##########################
# print(os.getcwd()) #当前工作空间目录
# os.chdir("d:") #改变当前的工作目录为 d:盘根目录
# os.mkdir("书籍") #默认创建在当前工作目录
#################创建目录、创建多级目录、删除##########################
# os.mkdir("书籍") #创建
#os.rmdir("书籍") # 删除 #相对路径都是相对于当前的工作目录
# os.makedirs("电影/港台/周星驰") #创建多级目录
#os.removedirs("../电影/港台/周星驰") #删除多级目录,只能删除空目录
# os.makedirs("../电影/港台/周星驰") #../ 指的是上一级目录
#os.rename("电影","movie") #重命名
# dirs = os.listdir("movie") #列出一级子目录
# print(dirs)
#coding=utf-8
#测试os.parh中关于目录、路径的操作
# import os
import os.path # from os import path 也可以这样。这样是可以直接调用path.isabs()
###############判断:绝对路径、是否目录、是否文件、文件是否存在#########################
print(os.path.isabs("d:/a.txt")) #true 是不是绝对路径
print(os.path.isdir("d:/a.txt"))
print(os.path.isfile("d:a.txt"))
print(os.path.exists("d:/a.txt"))
################获得文件基本信息##################
print(os.path.getsize("b.txt")) #获取文件的大小
print(os.path.abspath("b.txt")) #获取文件的绝对路径
print(os.path.dirname("d:/a.txt")) #获取所在目录
print(os.path.getctime("b.txt")) #文件创建时间
print(os.path.getatime("b.txt")) #文件最后访问时间
print(os.path.getmtime("b.txt")) #文件最后修改时间
################对路径的操作#############################
path = os.path.abspath("b.txt")
print(os.path.split(path)) #切割路径,返回元祖。按文件路径和文件名切割
print(os.path.splitext(path)) # 按. 切割
print(os.path.join("aa","bb","cc")) #用分隔符连接
#coding=utf-8
#列出工作目录下所有的.py文件,并输出文件名
import os
path = os.getcwd() #获得当前工作空间目录
file_list = os.listdir(path) #列出子目录、子文件
for filename in file_list:
if filename.endswith("py"):
print(filename)
print("############################")
file_list2 = [filename for filename in os.listdir(path) if filename.endswith("py")] #推导式。直接找出只含有py后缀的文件
for f in file_list2:
print(f)
#coding=utf-8
#测试os.walk()递归遍历所有的子目录和文件
import os
all_files = []
path = os.getcwd()
list_files = os.walk(path)
for dirpath,dirname,filenames in list_files:
for dir in dirname:
all_files.append(os.path.join(dirpath,dir))
for file in filenames:
all_files.append(os.path.join(dirpath,file))
#打印所有的子目录和文件
for f in all_files:
print(f)
exception
#coding=utf-8
#Traceback追溯,追根溯源。most recent call last最后一次调用
"""
try:
被监控可能引发的异常语句块
except BaseException as e:
异常处理语句块
"""
while True:
try:
x = int(input("请输入一个数字:"))
print("输入的数字:",x)
if x == 88:
print("退出程序!")
break
except BaseException as e:
print(e)
print("输入格式错误!请输入数字!")
print("循环数字输入程序结束!")
#coding=utf-8
#测试try...多个except结构
#先子类,后父类,针对性的写出错误
try:
a = input("请输入一个被除数:")
b = input("请输入一个除数:")
c = float(a)/float(b)
print(c)
except ZeroDivisionError:
print("异常。不能除以0")
except ValueError:
print("异常。不能将字符串转换成数字")
except NameError:
print("异常。变量不存在")
except BaseException as e:
print(e)
#coding=utf-8
#测试try...except...else结构 如果发生异常,执行except。如果没有,执行else
# try:
# a = input("请输入一个被除数:")
# b = input("请输入一个除数:")
# c = float(a)/float(b)
# except BaseException as e:
# print(e)
# else:
# print(c)
#测试try...except...else...finally结构 如果发生异常,执行except。如果没有,执行else。最终执行finally
try:
a = input("请输入一个被除数:")
b = input("请输入一个除数:")
c = float(a)/float(b)
except BaseException as e:
print(e)
else:
print(c)
finally:
print("程序结束!")
#coding=utf-8
#测试traceback模块的使用
import traceback
#
# try:
# print("step1")
# num=1/0
# except:
# traceback.print_exc()
#############将异常信息输出到指定文件中#################
try:
print("step1")
num=1/0
except:
with open("a.txt","a") as f:
traceback.print_exc(file=f)
GUI
# coding=utf-8
from tkinter import *
from tkinter import messagebox
import os
root = Tk()
root.title("我的第一个DUI程序")
root.geometry("500x300+200+200") # 调整窗口
btn01 = Button(root)
btn01["text"] = "点我就送花"
btn01.pack()
def songhua(e): # e就是事件对象
messagebox.showinfo("Message", "送你99朵玫瑰花,亲亲我吧!")
print("送你99朵玫瑰花")
btn01.bind("<Button-1>", songhua)
root.mainloop() # 调组件的 mainloop() 方法,进入事件循环
# coding=utf-8
"""测试一个经典的GUI程序写法,使用面向对象的方式"""
from tkinter import *
from tkinter import messagebox
class Application(Frame): # 这里的Application指的是GUI应用程序。也可以自定义
"""一个经典的GUI程序写法"""
def __init__(self, master=None):
super().__init__(master) # super()代表的是父类的定义,而不是父类对象
self.master = master
self.pack()
self.createWidget()
def createWidget(self):
"""创建组件"""
self.btn01 = Button(self)
self.btn01["text"] = "点我就送花!"
self.btn01.pack()
self.btn01["command"] = self.songhua
# 创建一个退出按钮
self.btnQuit = Button(self, text="退出", command=root.destroy)
self.btnQuit.pack()
def songhua(self):
messagebox.showinfo("送花", "送你99朵玫瑰花")
if __name__ == '__main__':
root = Tk()
root.geometry("500x300+200+200")
root.title("一个经典的GUI程序测试")
app = Application(master=root)
root.mainloop()
# coding=utf-8
"""测试label组件的基本用法,使用面向对象的方式"""
from tkinter import *
from tkinter import messagebox
class Application(Frame):
"""一个经典的GUI程序写法"""
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.createWidget()
def createWidget(self):
"""创建组件"""
self.label01 = Label(self, text="百战程序员", width=10, height=2,
bg="blue", fg="white")
self.label01.pack()
self.label02 = Label(self, text="杨自学", width=10,height=3,
bg="yellow", fg="white", font=("黑体", 30))
self.label02.pack()
# 显示图像
global photo # 把photo对象声明成全局变量,如果是局部变量,本方法执行完毕后,图像销毁,窗口显示不出
photo = PhotoImage(file="puke/aaa.gif")
self.label03 = Label(self, image=photo)
self.label03.pack()
self.label04 = Label(self, text="北京尚学堂\n我的自学\n加油!!!",
borderwidth=3, relief="solid", justify="right")
self.label04.pack()
if __name__ == '__main__':
root = Tk()
root.geometry("500x700+300+200")
app = Application(master=root)
root.mainloop()
# coding=utf-8
from tkinter import *
from tkinter import messagebox
class Application(Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.createWidget()
def createWidget(self):
"""创建组件"""
self.but01 = Button(self, text="登录", command=self.login, width=20, height=3, anchor=E)
self.but01.pack()
global photo
photo = PhotoImage(file="puke/aaa.gif")
self.but02 = Button(root, image=photo, command=self.login)
self.but02.pack()
#self.but02.config(state="disabled") # 设置禁用按钮
def login(self):
messagebox.showinfo("尚学堂系统", "登录成功!")
if __name__ == '__main__':
root = Tk()
root.geometry("500x300+200+200")
app = Application(master=root)
root.mainloop()
# coding=utf-8
"""测试Entry组件的基本用法,使用面向对象的方式"""
from tkinter import *
from tkinter import messagebox
class Application(Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.createWidget()
def createWidget(self):
"""创建登录界面的组件"""
self.label01 = Label(self, text="用户名")
self.label01.pack()
# StringVar变量绑定到指定的组件。
# StringVar变量的值发生变化,组件也发生变化;
# 组件内容发生变化,StringVar变量的值也发生变化
v1 = StringVar()
self.entry01 = Entry(self, textvariable=v1)
self.entry01.pack()
# 获取账户
v1.set("admin")
print(v1.get())
print(self.entry01.get())
# 创建密码框
self.label02 = Label(self, text="密码")
self.label02.pack()
v2 = StringVar()
self.entry02 = Entry(self, textvariable=v2, show="*")
self.entry02.pack()
Button(self, text="登陆", command=self.login).pack() # 简写
def login(self):
username = self.entry01.get()
pwd = self.entry02.get()
print("去数据库比对用户名和密码")
print("用户名:"+username)
print("密码:"+pwd)
if username == "123456" and pwd == "123":
messagebox.showinfo("尚学堂学习系统", "登录成功!")
else:
messagebox.showinfo("尚学堂学习系统", "登录失败,用户名或者密码错误")
if __name__ == '__main__':
root = Tk()
root.geometry("400x130+200+300")
app = Application(master=root)
root.mainloop()
# coding=utf-8
"""测试text多行文本定义"""
from tkinter import *
class Application(Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.createWidget()
def createWidget(self):
self.w1 = Text(root,width=40,height=12,bg="yellow")
# 宽度20个字母(10个汉字),高度一个行高
self.w1.pack()
# 行从1开始,列从0开始
self.w1.insert(1.0, "012345\n6789") # 在1行0列插入字符串
self.w1.insert(2.3, "锄禾日当午,汗滴禾下土。是指盘中餐,粒粒皆辛苦\n")
if __name__ == '__main__':
root = Tk()
root.geometry("400x300+300+300")
app = Application(master=root)
root.mainloop()
未完