一、窗体
1.组件
1.1窗体居中
from tkinter import *
class mainWindow():
def __init__(self):
self.mainwin = Tk()
method.tk_size(win=self.mainwin, ww=400, wh=600, xr=2, yr=2, t='首页')
self.mainwin.mainloop()
class method():
#设置窗体
def tk_size(win,t,ww,wh,xr,yr):
win.title(t)
sw = win.winfo_screenwidth()
sh = win.winfo_screenheight()
x = (sw - ww) / xr
y = (sh - wh) / yr
win.geometry("%dx%d+%d+%d" % (ww, wh, x, y))
win.resizable(0, 0)
win.resizable(0, 0)
mainWindow()
1.2多选框
from tkinter import *
class mainWindow():
def __init__(self):
self.mainwin = Tk()
method.tk_size(win=self.mainwin, ww=400, wh=600, xr=2, yr=2, t='抓取日志工具--V1.0')
v1 = IntVar()
v2 = IntVar()
v3 = IntVar()
v4 = IntVar()
Chkeckbottn1 = Checkbutton(self.mainwin, text='一', variable=v1, onvalue=1, offvalue=0)
Chkeckbottn1.place(x=110, y=66, width=45, height=30, )
Chkeckbottn2 = Checkbutton(self.mainwin, text='二', variable=v2, onvalue=1, offvalue=0)
Chkeckbottn2.place(x=170, y=66, width=45, height=30)
Chkeckbottn3 = Checkbutton(self.mainwin, text='三', variable=v3, onvalue=1, offvalue=0)
Chkeckbottn3.place(x=225, y=66, width=45, height=30)
Chkeckbottn4 = Checkbutton(self.mainwin, text='ALL', variable=v4, onvalue=1, offvalue=0, command=lambda: method.tk_SelectAll(s=v4.get()))
Chkeckbottn4.place(x=275, y=66, width=45, height=30)
self.mainwin.mainloop()
class method():
#设置窗体
def tk_size(win,t,ww,wh,xr,yr):
win.title(t)
sw = win.winfo_screenwidth()
sh = win.winfo_screenheight()
x = (sw - ww) / xr
y = (sh - wh) / yr
win.geometry("%dx%d+%d+%d" % (ww, wh, x, y))
win.resizable(0, 0)
win.resizable(0, 0)
#多选框设置全选
def tk_SelectAll(s):
if s == 1:
Chkeckbottn1.select()
Chkeckbottn2.select()
Chkeckbottn3.select()
Chkeckbottn4.select()
elif s == 0:
Chkeckbottn1.deselect()
Chkeckbottn2.deselect()
Chkeckbottn3.deselect()
1.3Text文本框
from tkinter import *
class mainWindow():
def __init__(self):
self.mainwin = Tk()
method.tk_size(win=self.mainwin, ww=400, wh=600, xr=2, yr=2, t='抓取日志工具--V1.0')
textinfo = Text(width=53, height=30)
textinfo.place(x=10, y=180)
#按钮
Button(self.mainwin, text="提交", width=140, height=60, command:self.commit).place(x=60, y=118, width=61, height=30)
#设置文本颜色
textinfo.tag_config("t3", backgroun="moccasin")
textinfo.tag_config("t2", backgroun="lightcoral")
textinfo.tag_config("t1", backgroun="lightgreen")
#文本禁止选项
# self.Text.config(cursor="none") #隐藏鼠标
# self.Text.bind('<KeyPress>', lambda e: 'break') #禁止键盘输入
# self.Text.bind('<Button-1>', lambda e: 'break') # 禁止鼠标左键
# self.Text.bind('<B1-Motion>', lambda e: 'break') # 禁止鼠标左键移动
# self.Text.bind('<Double-Button-1>', lambda e: 'break') # 禁止双击鼠标左键
self.mainwin.mainloop()
def commit(self):
#清空
textinfo.delete(0.0, END)
#插入
textinfo.insert(INSERT, '--->插入的文本,亮绿色<---\n', "t1")
#显示最后行
textinfo.see(END)
mainWindow()
1.4选择文件路径
from tkinter.filedialog import askdirectory
#设置文件路径
def tk_SelectPath(self):
global path_
path_ = askdirectory() # 使用askdirectory()方法返回文件夹的路径
if path_ == "":
pass
else:
path_ = path_.replace("/", "\\") # 实际在代码中执行的路径为“\“ 所以替换一下
EntryPath.delete(0, END)
EntryPath.insert(INSERT, path_)
2.连接数据库
2.1连接mysql数据库建表
def creat_table(self):
#打开数据库连接
db = pymysql.Connect(
host='192.168.1.100',
port=3306,
user='root',
passwd='123456',
db='test',
charset='utf8'
)
#创建游标对象
cursor = db.cursor()
#建表语句
sql = """CREATE TABLE IF NOT EXISTS GetWeather (
cityid int(30) not null,
date char(60),
week char(60),
update_time char(60),
city char(60),
aqi char(60)
)DEFAULT CHARSET=utf8;
"""
#执行
cursor.execute(sql)
print("CREATE TABLE OK")
#关闭数据库连接
db.close()
2.2mysql执行增、删、查、改操作
# 带参数的精确查询
def query(sql,*keys):
db=open() # 连接数据库
cursor = db.cursor() # 使用cursor()方法获取操作游标
cursor.execute(sql,keys) # 执行查询SQL语句
result = cursor.fetchall() # 记录查询结果
cursor.close() # 关闭游标
db.close() # 关闭数据库连接
return result # 返回查询结果
# 执行数据库的增、删、改操作
def exec(sql,values):
db=open() # 连接数据库
cursor = db.cursor() # 使用cursor()方法获取操作游标
try:
cursor.execute(sql,values) # 执行增删改的SQL语句
db.commit() # 提交数据
return 1 # 执行成功
except:
db.rollback() # 发生错误时回滚
return 0 # 执行失败
finally:
cursor.close() # 关闭游标
db.close() # 关闭数据库连接
3. paramiko
3.1远程执行命令
#获取目录
def tk_Connect_service(cmd):
#获取远程服务器IP
mcsip = EntryMSCIP.get()
# 获取SSHClient实例
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接SSH服务端
client.connect(mcsip, username="root", password="Password", port=22)
#支持ls命令
stdin, stdout, stderr = client.exec_command(command=cmd)
result = stdout.read().decode('utf-8')
i = ' '.join(result.split())
s = i.split(' ')
client.close()
return (s,i)
3.2远程下载文件
def tk_Download(v):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(v, username="x", password="x", port=22)
l = listbox2.get(0, END)
textinfo.insert(INSERT, '---->请稍等<----\n', "t3")
for d in l:
date = datetime.datetime.now().strftime('%Y-%m-%d--%H-%M-%S')
time.sleep(1)
cmd1 = 'find /home -type d -name %s' % d
path, p = method.tk_Connect_service(cmd=cmd1)
cmd2 = 'tar -cvf %s/%s.tar %s' %(p, date, p)
stdin, stdout, stderr = client.exec_command(cmd2)
result = stdout.read().decode('utf-8')
tran = client.get_transport()
sftp = paramiko.SFTPClient.from_transport(tran)
remotepath = '%s/%s.tar' %(p, date)
localpath = r'C:\Users\admin\Desktop\%s.tar' %date
cmd3 = 'find %s/%s.tar' %(p, date)
stdin3, stdout3, stderr3 = client.exec_command(cmd3)
result3 = stdout3.read().decode('utf-8')
if result3 != 0:
#textinfo.insert(INSERT, '%s\n' % (result))
textinfo.insert(INSERT, '压缩日志文件为%s.zip\n' %date, "t5")
textinfo.insert(INSERT, '成功\n', "t3")
textinfo.focus_force()
textinfo.see(END)
textinfo.update()
else:
textinfo.insert(INSERT, '失败\n', "t3")
textinfo.see(END)
sftp.get(remotepath, localpath, callback=method.tk_progress_bar)
method.tk_jdt(d=date)
cmd4 = 'rm -rf %s/%s.tar' %(p, date)
stdin4, stdout4, stderr4 = client.exec_command(cmd4)
client.close()
4.其他
4.1输入IP格式判断
def tk_Check_Ip(self):
#获取输入框IP
v = EntryMSCIP.get()
p = re.compile('^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$')
if p.match(v):
textinfo.insert(INSERT, '--->正确格式的IP<---\n', "t1")
return True
else:
textinfo.insert(INSERT, '--->不正确格式的IP<---\n', "t2")
return False
4.2命令运行过程较长,窗体无响应
from tkinter import *
import threading
class mainWindow():
def __init__(self):
self.mainwin = Tk()
method.tk_size(win=self.mainwin, ww=400, wh=600, xr=2, yr=2, t='抓取日志工具--V1.0')
Button(self.mainwin, text="提交", width=140, height=60, command=lambda: MyThread(self.commit)).place(x=60, y=118, width=61, height=30)
def commit(self):
pass
#继承 threading.Thread 类
class MyThread(threading.Thread):
def __init__(self, func, *args):
super().__init__()
self.func = func
self.args = args
self.setDaemon(True)
self.start() # 在这里开始
def run(self):
self.func(*self.args)
4.3获取天气AIP
def request_data(self):
city = EntryCity.get()
print(city)
url = 'https://v0.yiketianqi.com/api?
unescape=1&version=v61&appid=‘id’&appsecret=‘密码’&city=%s' % city
req = requests.get(url, timeout=30) # 请求连接
req_jason = req.json() # 获取数据
v = req_jason.values()
print(req_jason)
textinfo.insert(INSERT, v)
5.adb远程安卓
5.1检查adb
def tk_Check_Adb(self):
#确定远程端口
port = method.tk_Check_AdbPort(self=self)
#获取远程IP
mcsip = EntryMSCIP.get()
#关闭服务
os.system('cd %s && adb kill-server' % (path))
#adb版本
textinfo.insert(INSERT, '--->adb版本<---\n', "t3")
c1 = 'cd %s && adb version | findstr "Version"' %(path)
#参考5.2cmd命令执行方法
method.tk_ExecCmd(cmd=c1)
textinfo.insert(INSERT, '--->请稍等<---\n', "t3")
#adb连接
c2 = 'cd %s && adb connect %s:%s' %(path, mcsip, port)
method.tk_ExecCmd(cmd=c2)
#连接状态判断
c3 = 'cd %s && adb devices | findstr %s' %(path, mcsip)
adb_status = os.system(c3)
if adb_status != 0:
textinfo.insert(INSERT, '--->adb连接异常<---\n', "t2")
return 0
else:
textinfo.insert(INSERT, '--->adb连接正常<---\n', "t1")
5.2执行本地cmd命令并输出内容(Popen)
def tk_ExecCmd(cmd):
r = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while True:
result = r.stdout.readline() # 默认获取到的是二进制内容
if result != b'': # 获取内容不为空时
try:
p = (result.decode('gbk').strip('\r\n')) # 处理GBK编码的输出,去掉结尾换行
textinfo.insert(INSERT, '%s\n' % (p))
textinfo.focus_force()
textinfo.see(END)
textinfo.update()
except:
p = (result.decode('utf-8').strip('\r\n')) # 如果GBK解码失败再尝试UTF-8解码
textinfo.insert(INSERT, '%s\n' % (p))
textinfo.focus_force()
textinfo.see(END)
textinfo.update()
else:
break
6.字符串、list、字典处理
6.1list与字符串
COLstr2 = 'cityid, date, week, update_time, city, cityEn, country, countryEn, wea, wea_img, tem, tem1, tem2, win, win_speed'
#以英文的,为分隔符,得到list
COLstr2.split(",")
参考:python中list与string的转换_bufengzj的博客-CSDN博客_python 列表转字符串
6.2字符串替换字符
#!/usr/bin/python
str = "this is string example....wow!!! this is really string";
print str.replace("is", "was");
print str.replace("is", "was", 3);
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string