Python常用代码

基本用法

grid,pack,place用法参考
方法:根据某个元素排序等各类排序方法

#string and values
tag = 'tag_odd' if i%2 == 1 else 'tag_even'			带判断的赋值
str = str.split(",")								用逗号将str拆成list
str = ','.join(list)								用逗号将list合并成str
x = x.strip()										去除头尾的空格
value = eval(str)									str转回对应数据格式
abs(i)											绝对值
os.makedirs(path) 									创建路径
os.getcwd()										获取当前路径
os.remove(path)									删除指定文件
os.rename(oldname,newname)						重命名
files = os.listdir(path)							列出路径下所有文件名

# 获取用户输入十进制数
dec = int(input("输入数字:"))
print("十进制数为:", dec)
print("转换为二进制为:", bin(dec))
print("转换为八进制为:", oct(dec))
print("转换为十六进制为:", hex(dec))

# 二进制转十进制
A_2 = "101" # 1. 字符串类型
A_10 = int(A_2, 2)
A_2 = 0b101 # 2. 数值类型
A_10 = int(A_2)

#list
x = [i for i in range(0,10)]								创建list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
import random
random.uniform(1, 10)										生成 [1, 10] 内的均匀分布随机数
random.randint(1, 10)										生成 [1, 10] 内的随机整数
random.sample(population,k)									随机取n个样本
random.shuffle(listx, random=None)							乱序重拍
marks = sorted(marks,key=lambda mark: mark[1])			**	根据某个元素排序
l.remove('x')							删除某值元素
l.remove(np.nan)						删除nan
l.insert(0,a)							在首位插入元素
del(l[-1])								删除最后一位元素
l.count(A):							输出元素A在列表l里面出现的次数
l.index(A):							输出元素A在列表l里面的索引位置号
l.index(A,a,b):						对于列表m里面包含多个元素A时,输出在列表m索引号a-b之间的特定索引号
l.reverse():							将列表m进行前后的翻转,前变后,后变前
l.sort():								将列表m里面地数据进行从小到大的排列
l.sort(reverse=True):					将列表m里面地数据进行从大到小的排列
N=M[:]														深拷贝
N=M															浅拷贝

#放置
<<grid>> -column, -columnspan, -in, -ipadx, -ipady, -padx, -pady, -row, -rowspan, or -sticky
x.grid(row=0,column=2,sticky=('E,S'),columnspan=2)

x.place(relx=0,rely=0,anchor='w',x=x, y=y)
x.pack(anchor='w')

# 批量读写
if s[0].winfo_class()=='TEntry':
	s[0].delete(0,END)
	s[0].insert(0,str(v))
	print('TEntry')
elif s[0].winfo_class()=='Text':
	s[0].delete('1.0','end')
	s[0].insert(END,v)
	print('Text')
elif s[0].winfo_class()=='TCombobox':
	s[0].set(v)
	print('TCombobox')
elif s[0].winfo_class()=='TButton':
	print('TButton')
	
# 显示格式
bfb= '{:.2%}'.format(a/b)					显示x.xx%
bfb= '({:.0%})'.format(a/b)					显示x%
data[u'线损率'] = data[u'线损率'].apply(lambda x: format(x, '.2%')) 

DataFrame & pandas & numpy

python 计算均值、方差、标准差 Numpy,Pandas

# 新建
df = pd.DataFrame({'column1':list1,'column2':list2})				新建dataframe(*series与list皆可)
df = pd.DataFrame(list(zip(series_1, series_2)))					
df.to_csv(path)														新建csv文件
df.to_excel(path)													新建xlsx文件

# 导入------------------------------------------------------------------------------------------------
df = pd.read_csv(path)												导入csv文件
df = pd.read_excel(path)											导入excel文件
df.columns = ['Close', 'Overme']									重命名所有标题
df.rename(columns={'date': 'Date','open': 'Open'},inplace=True)		替换指定标题(替换原标题)
df['Date'] = pd.to_datetime(df['Date'], format='%Y/%m/%d')		文字转日期
x.loc[:,'start_time'] = pd.to_datetime(x.loc[:,'start_time']) 		【改良版】
data['note_n'] = pd.to_numeric(data['note_n']) 				文字转数字
df.set_index('Date', inplace=True)        				日期为索引(替换原索引)



# 查看-------------------------------------------------------------------------------------------------
df.info																(属性不需要括号)
df.info()															字节等信息
df.head(n)															前n行
df.tail(n)															后n行
df.dtypes															了解每列的数据格式
df.shape	//df.shape[0]//df.shape[1]								获取行列数//行数//列数
df.index															获得索引整列
df.columns															获得所有列名
df.values															每行的values
df.describe()													**	统计所有数值元素的基本情况

for colname in df():												根据列名遍历		
for index, rowinfo in df.iterrows():								根据行信息遍历

# nan处理----------------------------------------------------------------------------------------------
np.isnan(value)													**  判断元素是否是nan,返回True/False
df.fillna(0,inplace=True)											所有nan值换成0,且替换原dataframe
df['a'].fillna(0,inplace=True)										填充指定列
df.dropna(axis=0,hoe='any')		how='any'/'all'						纵向查看,有nan就把这行drop掉
df.isull()															返回每个元素的布林值
np.any(df.isnull()==True)											判断整个df是否有nan值,返回True/False

# 赋值-------------------------------------------------------------------------------------------------
df.iloc[3,1] = 111													指定位置赋值
df.loc['20200101','a']												指定标签赋值
df[df.a > 0] = 0													批量赋值a列>0的所有行
df.b[df.a > 0] = 0												**	↑,但只赋值b列而不是整行

# 操作(属性、运算、loc、iloc、筛选)------------------------------------------------------------------
## Series (线性数据)
s = pd.Series([1,3,6,np.nan,44,1])								**	同一维array一样都可通过list(x)转为list
s = pd.Series(np.random.randn(1000),index=np.arange(1000))
s = s.cumsum() + s.plot() + plt.show()								累计求和并直接plot+show

## DataFrame
df = pd.DataFrame(np.random.randn(7,4),index=dates,columns=['a','b','c','d'])
df = pd.DataFrame(np.arange(12).reshape((3,4)))					**	生成(无index无columnname)
dates = pd.date_range('20200101',periods=7)						**	生成(日期为index,abcd分别为columnname)
df = df.cumsum() + df.plot() + plt.show()							逐列分别累计求和并直接plot+show
df.shift(periods=1, freq=None, axis=0)								整个df平移

df[0:1]0行
df[-1:]																最后一行
df[:2]2行之前(不含第二行)
df[1:3]																取指定多行 
df.iloc[3,1] 													**	(根据位置)取第4行第2个元素// 
df.iloc[3:5:1:3]													指定位置切片
df.iloc[[1,3,5],[1:3]]												不连续(隔行)筛选
df.loc[:,['aaa','bbb']]												(根据索引)取指定多列
df['20190101':'20190203']										**	根据日期切片(前提index是日期)
df['aaa']	= df.aaa											**	获得指定整列返回Series(两种写法)
list(data.loc[:,'Date_Time'])[0]								*** 日期序列的第一个值
df.loc['20200101']													获得指定整行返回Series
df.loc[0,'name']												**	指定行列数据值
df.loc[0:2,  ['name','age']]										获得第0-2行,name和age列的数据
df,loc[[0:3],['name','age']]
df.loc[df['gender']=='M','name']								** 	获取gender列是M的name列数据	
df.loc[df['gender']=='M',['name','age']								获取gender列式M的name与age列数据	
df.ix[:3,['a','b']													混合筛选,前为position,后为label	
df.loc[len(df),'ttcode']=ttcode									** 	为新增行赋值

df.T																转置(行列互换)
df = df.iloc[::-1]													将整个df逆序
df.drop_duplicates(['name'])									**	列有重复,即删掉重复的整行
df['column'].unique()											**	某列不重复值
df['column'].value_counts()											某列值统计
df['diff'].sum()													某列值加总
df['a']+df['b']														a列与b列求和
a = s.astype(str) + d.astype(str)									字符串合并
df=df['北向资金今日增持估计-市值']/100000000						整列除以1亿,获得新df
df=df[df['aaa']=='xxx']	// df[df.a > 8]							**	单条件筛选数据						
df=df[(df.aaa=='x') & (df.bbb=='y')]								多条件筛选数据
df=df[df['aaa'].str.contains(x_find,regex=False)]					模糊查找相关行(声明非正则表达式)
df=df['序号'].isin(list_a)											筛选某列满足一系列值的数据
df=df[df['序号'].isin(list_a)]										同上条件,返回所有列
df=df[df['更新日期']<=today]										筛选满足日期条件的数据
r=np.where(df['aaa']==1)[0][0]	//	df[r:r+1]						查找行号,返回tuple[0][0] // 行切片
【index从0开始才可以用】

df.sort_index(axis=1,ascending=False)							**	根据横向列名降序排列(不写默认升序)
df.sort_values(by="column" , ascending=False) //True 			**	按某列值降序//升序排列
				# 必须是双引号
df.values.tolist()													dataframe转list
df['e'] = np.nan													新增一列全部为nan
df['name']=Series_a												**	最右新增一列(元素数量/索引一致)
df = pd.concat([df1,df2,df3],axis=0,ignore_index=True)			**	综合合并df并重新排序
df = pd.concat([df1,df2],join='inner') //'outer'					并集//交集合并df
df = pd.concat([df1,df2],axis=1)									横向合同,无数据用nan填充	
								,join_axes =[df1.index])			同上,但只用df1的index

df["ydate"] =df["y"].map(str) +"-"+ df["date"].map(str)  			两列文字合并
df['e'] = pd.Series([1,2,3,4,5,6],index=pd.date_range('2020101',periods=6)	最右添加列:index及数量一致才可以添加一列
df['x'] = pd.Series({'red':100,'blue':200,'green':300})				创建一个Series
s1 = pd.Series([1,2,3,4],index=['a','b','c','d'])					最末添加行Series
df = df1.append(s1,ignore_index=True)								
df = df1.append(df2,ignore_index=True)								最末添加DataFrame
df = df1.append([df2,df3],ignore_index=True)						最末添加2个DataFrame
df = df.assign(ClosePrice=pd.Series(df['Close'], index=df.index))	添加列,索引不变
df = df.assign(FastEMA10d=pd.Series(ema_fast_values, index=df.index))

pd.merge(df1,df2,on='key')											在key列上重叠合并
pd.merge(df1,df2,on=['col1','col2'],how='inner') //'outer,left,right'在多列上合并,并选择how
pd.merge(df1,df2,on='col1',indicator='xxx'//True)					最右生成合并方式,列名为xxx//_merge
pd.merge(df1,df2,left_index=True,right_index=True,how='outer')	**	根据index合并

# numpy----------------------------------------------------------------------------------------------
np.array(m)														转矩阵
np.zeros( (3,4) ) 													生成全0矩阵
np.ones( (3,4), dtype=np.int64)										生成全1矩阵
np.arange(10, 20, 2)												起、止、步长
np.arange(12).reshape( (3,4))										线性数据转矩阵
np.linspace(1,10,6).reshape((2,3))							

m < 3  // a == 3													返回每个元素布林值
np.sort(m)															矩阵逐行排序
np.sin(m)		
np.argmin(m)														矩阵最小元素的索引(返回int值)
np.argmax(m)														矩阵最大元素的索引
np.mean(m)	=  m.mean()												矩阵的平均值(两种写法皆可)
np.mean(m, axis = 0)											**	逐列求平均值
np.mean(m, axis = 1)												逐行求平均值
np.average(m)														同上
np.average(a, weights = [1, 2, 1, 1])								加权平均
np.median(m)														中位数
np.percentile(b,q=percent)  										百分位
np.var()  															求方差
np.std() 															求标准差
np.cumsum(m)														累计求和
np.diff(m)2个元素之间求差
np.nonzero(m)														分别输出非0元素的行/列的索引
np.prod()		函数用来计算所有元素的乘积,对于有多个维度的数组可以指定轴,如axis=1指定计算每一行的乘积
np.clip(m,x,y)														大于y都为y;小于x都为x;其他不变
np.transpose(m) = m.T												矩阵转置(两种写法皆可)

m[1][1]	= m[1,1]													索引:先行后列
m[:,1]															**	第一列所有(:代表所有)
m[2,;]																第一行所有
m[1,1:3]															返回指定位置元素的list
d[1:3] = [22,33]												**	将第2/3个元素更改为22/23
# 循环技巧
for row in m:														默认逐行迭代
for col in m.T:														通过转置逐列迭代
for item in m.flatten():											每个元素迭代
m.flat																返回迭代器?

b = a.copy() 													**	deep copy(a变b不变)
np.concatenate((a1, a2, ...), axis=0)							**	多数列,列方向合并
							  axis=1)										行方向合并
np.vstack((a1,a2))													纵向合并array
np.hstack((a1,a2))													横向合并array
np.split(a,2,	axis = 0)										**	纵向逐列切两段(水平分两部分)
				axis = 1)											横向逐行切两段(垂直分两部分)
np.vsplit(a,2)														纵向分割
np.hsplit(a,2)														横向分割
np.array_split(a,3,axis = 1)									**	不能均分时,多余1的给到第1...	
				
m[np.newaxis,]														横向数列,新增维度变二维
m[:,np.newaxis]														横向数列转纵,新增维度变二维
a*b ≠ np.dot(a,b)	= a.dot(b)									**	矩阵的两种相乘方法

DataFrame聚合

方法:groupby对象
方法:Offset Aliases采样频率
方法:rollong窗口函数(移动平均)

df_max = data.High.resample('1W').max()								按照频率合并
df.groupby(['col1', 'col2'])['col3'].rolling('3s').sum()			根据指定列名、指定频率合并指定列值

Label 与 Paned Windows 固定界面

ttk.Labelframe
std options: labelanchor, text, underline, padding, labelwidget, width,height

# fix frame
for i in range(30):
		tk.Label(self,text=i,fg=x,bg=y).grid(row=i,column=1)
	for i in range(16):
		tk.Label(self,text=i+2,width=5,fg=x,bg=y).grid(row=0,column=i+2,sticky=('W,E'))
			
lblue=()
lhead=('OVERVIEW')																
l_dic={'OVERVIEW':(2,1), 'code':(2,3), 'abb':(3,3), 'price':(4,3), 'chg':(5,3),
		 'vol':(6,3), 'GMV':(7,3), 'ROE':(8,3), 'PE':(9,3),'time%':(10,3),
		 'GM':(11,3),'debet ratio':(12,3),'cash flow':(13,3)}
# put words	
for i in range(len(l_dic)): 	#写Label(2)
	key=list(l_dic.keys())[i]
	c=l_dic[key][0]
	r=l_dic[key][1]
	if key in lblue:
		tk.Label(self,text=key,justify='left', anchor='w', relief='solid', borderwidth=0, width=13, height=1,fg='blue',bg='#E2EFDA').grid(row=r,column=c)
	elif key in lhead:
		tk.Label(self,text=key,justify='left', anchor='c', relief='solid', borderwidth=0, width=13, height=1,fg='white',bg=blue_h).grid(row=r,column=c)
	else:
		tk.Label(self,text=key,justify='left', anchor='c', relief='solid', borderwidth=0, width=15, height=1,fg='black',bg=grey_l).grid(row=r,column=c)

<<Panewindow>>
style = ttk.Style()
style.configure("fkit.TPanedwindow",background='#FCE4D6', relief=RAISED)
pwindow = ttk.Panedwindow(self,orient=HORIZONTAL, style="fkit.TPanedwindow",width=200,height=300)
pwindow.grid(column=11,row=6,columnspan=2,rowspan=8)
pwindow.pack(fill=BOTH, expand=YES,padx=20,pady=20)
pwindow.place(relx=0,rely=0,anchor='w',x=890, y=290)

<<Labelframe in Panedwindow>>
style = ttk.Style()
style.configure("index.TPanedwindow",background=blue_l, relief='groove')
pwx=450  
pwy=600	
pw = ttk.Panedwindow(self,orient='vertical', style="index.TPanedwindow",width=pwx,height=pwy)  
pw.grid(column=1,row=3,columnspan=5,rowspan=18)
f1 = ttk.Labelframe(pw, text='Pane1', width=pwx, height=pwy/2)
f2 = ttk.Labelframe(pw, text='Pane2', width=pwx, height=pwy/2)   
pw.add(f1)
pw.add(f2)

<<label显示图片>>
im=PIL.Image.open(path)
wo = im.width
ho = im.height
ratio = ho/wo
if wo/ho >= 0.3125:
	hs = 250
	ws = int(250/ratio)
else:
	ws = 800
	hs = int(800*ratio)
h = hs+50		# space for button
w = ws
im=im.resize((ws,hs),Image.ANTIALIAS)
self.win.geometry('%sx%s+1050+380'%(w,h))
img1=ImageTk.PhotoImage(im)
imglb1=tk.Label(self.win,image=img1)
imglb1.pack(side='left',fill='both')

Entry

var = StringVar()
e = tk.Entry(self, textvariable=username)
print('current value is %s' % name.get())
e.delete(0,'end')          # delete between two indices, 0-based
e.insert(0, 'your name')   # insert new text at a given index
passwd = tk.Entry(parent, textvariable=password, show="*")   # show ***

Combobox

var = tk.StringVar()
cb = ttk.Combobox(self, width=10,textvariable=var)
cb.grid(column=3,row=1,padx=1)
cb['values'] = ('USA', 'Canada', 'Australia')
cb.current(0)
cb.state(["readonly"])
cb.bind('<<ComboboxSelected>>', function)

cb.configure(state='disabled')
cb.configure(state='enabled')


# link values

Text

教程
方法:Text用法的总结(包括marker,tag等)
方法:应对行数变化的位置变化
案例:光标和see一起翻到指定的索引位置

t=tk.Text(win_bt,width=50,height=1,foreground=blue_h,font=font_1,
					background=blue_m,relief='groove')
# insertbackground 	插入光标的颜色,默认是黑色
# pady				Text 上/下框与文字最上/最下的间距
# selectbackground	被选取字符串的背景色彩
# selectforeground	被选取字符串的前景色彩
# state				输入状态,默认是NORMAL,表示可以输入,DISABLED则表示无法编辑
# wrap				可控制某行文字太长时的处理,当某行文字太长时,可从字符做断行,默认是wrap=CHAR,当wrap=WORD时,只能从字做断行
t.grid(column=3,row=3,columnspan=4,rowspan=4,sticky=('N,W,E,S'))
ys = ttk.Scrollbar(win_bt, orient = 'vertical', command = t.yview)
t['yscrollcommand'] = ys.set
ys.grid(column = 6, row = 3, sticky = 'N,E,S',rowspan=4)
# get
t.get(tk.SEL_FIRST, tk.SEL_LAST)					获得目前所选文字
t.index(tk.INSERT)									获得光标位置
t.index(tk.CURRENT)									
t.index(tk.END)										或得整个控件最后的位置索引
pos = t.search(key, start, tk.END)					查询指定文本的位置
def i2n(a):											位置转数字
	a=a.split('.')
	a[1]=float(a[1])
	a=float(a[0])*100+a[1]
	return a								

# mark
t.mark_set('markOne', 3.0)							指定位置设定marker
t.mark_set("insert", "%d.%d" % (row+1, col+1))
t.index('m1')										获取指定mark的所以
t.mark_gravity('INSERT','RIGHT')
t.mark_gravity('m1')
t.mark_unset('m1')

# tag
pos = [('1.0', '1.33'), ('1.0', '1.33')]							读取时注意用eval还原
t.tag_configure('red', foreground='red',background='yellow') 		设定标签
t.tag_add('red','1.0','3.2')										应用标签(指定位置)
t.tag_add('red',t.index(tk.SEL_FIRST),t.index(tk.SEL_LAST)	)		应用标签(光标位置)
t.tag_nextrange('tag1','1.0','end')									查找范围内第1个应用此标签的索引
t.tag_remove('tag1', '1.0', tk.END)									去除指定标签

Listbox

方法:组件介绍八 Listbox

lst = tk.Listbox(root, width=20,bg='skyblue')
os.chdir('D:\\Python...')
for filename in glob.glob("*.png"):
	lst.insert(tk.END, filename
n = lst.curselection()								显示选中的文字
markname = lst.get(n)
t.see(t.index(markname))							页面翻到mark对应的位置
listbox.delete(0, "end")
listbox.insert("end", newitem) #插入新的项目

Button & CheckButton

#1
b1	=Button(self,text=' Overview ',fg='white',bg='#20B2AA',	relief='groove',command=lambda: root.show_frame(PageOne)).grid()
#2
Button(self,text='FRESH',	width=12,	relief='groove',command=fresh_stkinfo,fg='white',bg='#4169E1')\
				.grid(column=2,row=24)

fg=‘white’,bg=‘#20B2AA’ 亮蓝色按钮

<<CheckButton>> 
s = StringVar(value="abc")   # default value is ''
b = BooleanVar(value=True)   # default is False
i = IntVar(value=10)         # default is 0
d = DoubleVar(value=10.5)    # default is 0.0
cb.select()					# 将lan_c_plus_plus设置为选中状态
cb.deselect()				# 将lan_c_plus_plus设置为未选中状态
cb.toggle()					# 切换lan_c_plus_plus的状态
chkbt['state'] = 'disabled' | 'normal' | 'active'
# sample --------------------------------------------------------------------------------
def do_index():	
	print(var.get()) #注意是var变量的get
var=tk.StringVar()
ca = Checkbutton(win,text='标签', variable=var, onvalue='级别', 	offvalue='', # 不要ttk
			command=do_index, bg=green_m, justify='left', anchor='w')\
			.grid(column=2,	row=6)

messagebox

messagebox.showinfo(message='已保存')
a=messagebox.askquestion('提示','是否保存并交卷?')
tk.messagebox.showerror(title='Hi',message='has error')
tk.messagebox.showwarning(title='Hi', message='has warning')

Dialog Windows

from tkinter import filedialog
filename = filedialog.askopenfilename()
filename = filedialog.asksaveasfilename()
dirname = filedialog.askdirectory()
# sample (link to button)
def get_savepath():
			savepath = filedialog.asksaveasfilename()+'.xlsx'     

tkinter

事件绑定
组件一览

window.attributes("-alpha", 0.5)		# Transparency
window.attributes("-fullscreen", 1)		# Full Screen
window.attributes("-topmost", 1)		# Stacking Order

frame

在tkinter内实现界面切换

frame = ttk.Frame(root)
frame['padding'] = (5,7,10,12) # left: 5, top: 7, right: 10, bottom: 12
frame['borderwidth'] = 2
frame['relief'] = 'sunken'
# change style
s = ttk.Style()
s.configure('Danger.TFrame', background='red', borderwidth=5, relief='raised')
ttk.Frame(root, width=200, height=200, style='Danger.TFrame').grid()

Canvas【包括图片显示类】

官方指导
Cancas Options

canvas = tk.Canvas(root,background='red')														创建
canvas.config(width=100,height=50)																尺寸
canvas = Canvas(parent, width=500, height=400, background='gray75')
canvas.create_line(10, 10, 200, 50, fill='red', width=3)										Line
canvas.create_rectangle(10, 10, 200, 50, fill='red', outline='blue')							Rectangle
canvas.create_oval(10, 10, 200, 150, fill='red', outline='blue')								Oval
canvas.create_polygon(10, 10, 200, 50, 90, 150, 50, 80, 120, 55, fill='red', outline='blue')	Polygon
canvas.create_arc(10, 10, 200, 150, fill='yellow', outline='black', start=45, extent=135, width=5)	Arc
myimg = PhotoImage(file='pretty.png')																Image
canvas.create_image(10, 10, image=myimg, anchor='nw')
canvas.create_text(100, 100, text='A wonderful story', anchor='nw', font='TkMenuFont', fill='red')	Text
b = ttk.Button(canvas, text='Implode!')																Widget
canvas.create_image(10, 10, anchor='nw', window=b)

# tkinter 中调用canvas 显示图片 (最初务必声明全局变量,self为界面切换用的frame)
global img2
img2 = None
def tes4():
			c1 = tk.Canvas(self,background='red')					# canvas 在frame中生成
			c1.grid(column=12,row=12,columnspan=3,rowspan=8)		# 放入界面frame中
			filename='D:\\Python\\001\\pic\\a666.png'
			global img2
			img2 = PhotoImage(file=filename,master=self)			# 调用图片在frame中
			print(img2.width())										# 测试用,确保img被传递
			c1.image=img2
			c1.create_image(10, 10, image=img2, anchor='nw')
*create_image -> anchor:n, ne, e, se, s, sw, w, nw, or center

# canvas 放进 frame
canvas = tk.Canvas(self, background='gray75')
canvas.create_arc(10, 10, 200, 150, fill='yellow', outline='black', start=45, extent=135, width=5)
canvas.grid(column=12,row=12,columnspan=6,rowspan=8,sticky='n,e,w,s')

# canvas 在 tkinter 中调用图片
global img
img = None
def tes2():
	root = tk.Tk()
	c1 = tk.Canvas(root,background='red')
	c2 =tk.Canvas(root,background='blue')
	c1.pack()
	c2.pack()
	filename='D:\\Python\\001\\pic\\a666.png'
	global img
	img = PhotoImage(file=filename,master=root)
	c2.create_image(10, 10, image=img, anchor='nw')

# 图片用label显示
im=PIL.Image.open(path)
global imglb1
global img1
img1=ImageTk.PhotoImage(im)
imglb1.destroy()
imglb1=tk.Label(self.win,image=img1)
imglb1.pack(side='left',fill='both')

# ----sample---------------------------------------------
from tkinter import *
from tkinter import ttk

def savePosn(event):
    global lastx, lasty
    lastx, lasty = event.x, event.y

def addLine(event):
    canvas.create_line((lastx, lasty, event.x, event.y))
    savePosn(event)

root = Tk()
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)

canvas = Canvas(root)
canvas.grid(column=0, row=0, sticky=(N, W, E, S))
canvas.bind("<Button-1>", savePosn)
canvas.bind("<B1-Motion>", addLine)

root.mainloop()

绑定 bind

Tkinter 常用绑定列表
Tkinter 鼠标键盘事件

ca_1j.bind("<<ComboboxSelected>>",change_1j)		# combobox被选择时
cb_code.bind("<Leave>",get_abb)						# 鼠标离开此组件时

鼠标事件:
 <Button-1>                                          鼠标左键单击    简写:<1>
 <Button-2>                                          鼠标中键单击    简写:<2>
 <Button-3>                                          鼠标右键单击    简写:<3>
 <B1-Motion>                                         鼠标左键拖动
 <B2-Motion>                                         鼠标中键拖动
 <B3-Motion>                                         鼠标右键拖动
 <ButtonRelease-1>                                   鼠标左键释放    简写:<1>
 <ButtonRelease-2>                                   鼠标中键释放    简写:<2>
 <ButtonRelease-3>                                   鼠标右键释放    简写:<3>
 <Double-Button-1>                                   鼠标左键双击
 <Double-Button-2>                                   鼠标中键双击
 <Double-Button-3>                                   鼠标右键双击
 <Enter>                                             鼠标指针进入控件
 <Leave>                                             鼠标指针离开控件
 键盘事件:
 <key>                                               任意键
 <Return>                                            回车
 <Left>                                              左箭头
 <Up>                                                上箭头
 <Right>                                             右箭头
 <Down>                                              下箭头
 窗体事件:
 <Configure>                                 改变大小或位置
 <Visibility>                                当组件变为可视状态时触发
 <Unmap>                                     当组件由显示状态变为隐藏状态时触发
 <Map>                                       当组件由隐藏状态变为显示状态时触发
 <Expose>                                    当组件从原本被其他组件遮盖的状态中暴漏出来时触发
 <FocusIn>                                   组件获得焦点时触发
 <FocusOut>                                  组件失去焦点时触发
 <Circulate>                                 当窗体由于系统协议要求在堆栈中置顶或压底时触发
 <Colormap>                                  当窗体的颜色或外貌改变时触发,Tk中忽略此细则
 <Property>                                  当窗体的属性被删除或改变时触发,属于TK的核心
 <Destroy>                                   当组件被销毁时触发
 <Activate>                                  与组件选项中的state项有关,表示组件由不可用变为可用时触发
 <Deactiavte>                                与组件选项中的state项有关,表示组件由可用变为不可用时候触发

【module】matlpotlib

画图种类:bar,hist,box,kde,area,scatter,hexbin,pie

# scatter
ax = data.plot.scatter(x='col1',y='col2',color='r',label='Class 1')
data.plot.scatter(x='col1', y='col2',color='g',label='Class 2',ax=ax)

官方图库:matplotlib
官方指导:pyplot.subplot
方法:matplotlib嵌入tkinter三种方法
方法:matplotlib键鼠响应事件
方法:使用GridSpec调整子图位置大小 (非对称的子图)
方法:横轴坐标间隔设定
方法:清除figure
案例:绘图双纵坐标轴设置及控制设置时间格式
案例:使用Matplotlib 画图 显示在tkinter 中的方法(class)
案例:随鼠标滑动自动标注代码
案例:动态刷新多个图标

import matplotlib.pyplot as plt
import matplotlib.dates as mdate				#显示坐标轴日期格式用

plt.clf()															去除fig
plt.savefig('D:\\python\\导出的图片.png')							保存图片
fig = plt.figure(num=1,figsize=(15,6))								生成fig(指定序号、尺寸)
plt.subplots_adjust(hspace=.4)										设定子图间距
ax1 = fig.add_subplot(111)											创建ax1
ax2 = fig.add_subplot(212,sharex=ax1)								创建ax2
plt.xlim((-1,2))													x轴取值范围
plt.ylim((-2,3))													y轴取值范围
plt.xlabel('i am x')												x轴描述
plt.ylabel('i am y')												y轴描述

plt.xticks(range(1, _scale+1, int(_interval)),  rotation=20) #s calendar.month_name[1:13],
plt.grid(b=_grid,which='major',axis='both',ls=_ls)

plt.grid(axis="y",c='r',ls='--',alpha=0.8)
plt.yticks(new_ticks)  // new_ticks=np.arange(-0.6,0.6,7)			换掉y轴ticks
plt.yticks([value_list],[text_list])								将y轴tick是换成文字	
--------------------
ax=plt.gca()														获得当前的坐标轴
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_postion('bottom')
ax.yaxis.set_ticks_postion('left')
ax.spines['bottom'].set_postion(('data',0)) //outward,axes

# 常用画法
x = np.linspace(-1,1,50)-1150条线段
plt.plot(x,y)
ax2.plot(x,df['Close'].rolling(window=70).mean(),color="blue",lw=1)	移动平均
-----------------------------sample(bar chart)-----------------------------------
n=12
X = np.arange(12)
Y1 = (1 - x/float(n))*np.random.uniform(0.5,1,n)
Y2 = (1 - x/float(n))*np.random.uniform(0.5,1,n)
plt.bar(X,+Y1,facecolor='#9999ff',edgecolor='white')
plt.bar(X,-Y2,facecolor='#ff9999',edgecolor='white')
plt.ylim((-0.15,0.15))
for x,y in zip(X,Y1):
	plt.text(x+0.1,y+0.01,'%.2f'%y,ha='center',va='bottom')
for x,y in zip(X,Y2):
	plt.text(x+0.1,-y-0.01,'-%.2f'%y,ha='center',va='top')
	
# 	l = [100,200,300,392,500]
# 	h = [20, 14, 38, 27, 9]
# 	_h= [-20,-34,-24,0,-8]
# 	w = [10 ,20, 30, 40, 50]
	b = [0]	*len(l)
	rects = ax3.bar(l, h, w, b,
               color='#ff9999',
               edgecolor='k',
               linewidth=0,
               xerr=4,
               #yerr=1,
               #ecolor='#999999',
               #capsize=10,
			   align='edge',
               #orientation='horizontal',
              )
	
-------------------------------------------------------------------------------
# 创建多个figure显示(不写num,顺序默认num)
plt.figure()		第一张
plt.plot(x,y1)		第一张对应画
plt.figure()		第二张
plt.plot(x,y2)		第二张对应画

# sample
import matplotlib.pyplot as plt
import numpy as np
import math
x = np.arange(0, math.pi*2, 0.05)
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
y = np.sin(x)
ax.plot(x, y)
ax.set_xlabel(‘angle’)
ax.set_title('sine')
ax.set_xticks([0,2,4,6])
ax.set_xticklabels(['zero','two','four','six'])
ax.set_yticks([-1,0,1])
plt.show()

# 先放labelframe用来放图
lframe = ttk.Labelframe(self, text='', width=800, height=300)
lframe.grid(column=2,row=14,columnspan=13,rowspan=10)
class From_Draw1:
	def __init__(self): 
		print('--------------------------------------initialization...')
		self.root=tk.Tk()               		#【放labelframe上去掉】创建主窗体	
		self.root.geometry('900x350+300+300')	#【放labelframe上去掉】			
		self.canvas=tk.Canvas()              	#【放labelframe上去掉】创建一块显示图形的画布
		self.figure=self.create_matplotlib()	# 返回matplotlib所画图形的figure对象
		self.create_form(self.figure)        	# 将figure显示在tkinter窗体上面
		self.root.mainloop()					#【放labelframe上去掉】			
		
	def create_matplotlib(self):				#画图过程
		#0)get scale,ma_period
		#1)data1   = ak.xxx()[-scale:]
		#2)Series1 = pd.to_numeric(data_bs.value, errors='ignore')/10000
		#3)ma
		ma=[]
		for i in range(scale):
			if i < p-1:
				ma.append(0)
			else:
				v=round(sbs[i-p+1:i+1].sum()/p,2)
				ma.append(v)
		#4)df['date'] = pd.to_datetime(df['date'], format='%Y/%m/%d')
		#5)df.set_index(['date'], inplace=True)
		#6)df = pd.DataFrame({'date':data1['date'], 'data1':series1, 'ma':ma})
		fig = plt.figure()													#1   设置画布
		plt.subplots_adjust(hspace=.4)										#	设置子图上下距离
		ax1 = fig.add_subplot(311, ylabel='%s 图1'%(code))					#2.1 画子图1 <<折线图>>
		ax1.set_title('北向资金今日增持估计-市值')								#	设置图1上方标题
		df['xxx'].plot(ax=ax1, color='black', lw=1., legend=True)				
		ax2 = fig.add_subplot(312, ylabel='图2', sharex=ax1)				#2.2 画子图2 <<柱状图>>
		df['xxx'].plot(ax=ax2,color='r', kind='bar', legend=True)			#(非共用横坐标去掉sharex即可)
		ax3 = fig.add_subplot(313, ylabel='图3', sharex=ax1)				#2.3 画子图3
		df['xxx'].plot(ax=ax3, color='b', lw=1., legend=True)
		
		locs, labels = plt.xticks()											#3	对多日期时设置坐标轴显示
		interval = (locs[-1]+1-locs[0]) // 20								#	无论样本量让坐标有20个区间
		ax3.xaxis.set_major_formatter(mdate.DateFormatter('%Y-%m-%d'))		#	设定第3子图x轴的日期显示格式
		plt.xticks(np.arange(locs[0], locs[-1]+1, step=interval),rotation=45)#	应用,并旋转45°
		
		for i in range(len(locs)):											#4	加标签(选择用)
		    plt.text(locs[i], 5-i/2, list(d_in10['增持市值'])[i],
		            fontsize=10, color = "r", style = "italic", weight = "light"
		            verticalalignment='top', horizontalalignment='center',rotation=0) 
		return fig															#5	返回(如调用,外部还要写一遍)
	
	def create_form(self,figure):
		self.canvas=FigureCanvasTkAgg(figure,self.root)						#【放labelframe上换对应lf】
		self.canvas.draw()
		self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
 		toolbar =NavigationToolbar2Tk(self.canvas, self.root) 				#【放labelframe上换对应lf】
		toolbar.update()
		self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)		#【放labelframe上去掉】	
# -----------------------------------------------------------------------------------------------
plt.subplots_adjust(hspace=.1)							调整子图的间距,hspace表示高(height)方向的间距
ax[0].set_ylabel('Close price in ¥')					y轴标题
ax[0].set_title('A_Stock %s MACD Indicator' % ttcode)	x轴标题

df['xxx'].plot(ax=ax1,color='black', lw=1.,legend=True)			折线图
df['xxx'].plot(ax=ax2,color='r', kind='bar', legend=True)		柱状图
#----------------------------------------------------------------------------------------------
Signature: plt.subplot(*args, **kwargs)					add a subplot to the current figure
Call:	subplot(nrows,ncols,index,**kwargs)
		subplot(pos,**kwargs)
		subplot(**kwargs)
		subplot(ax)
		
plt.subplot(221)  与  ax1=plt.subplot(2,2,1)			equivalent but more general
ax2=plt.subplot(221, frameon=False)						add a subplot with no frame
#------------------------------------
plt.grid(b=None,which='major',axis='both',**kwargs)				增加网格线

【module】tree

dfho = pd.DataFrame.from_dict(ast._history_orders,orient='index')
dfho['orders']=dfho.index
dfho['Seq']=np.arange(len(dfho))
dfho.set_index('Seq',inplace=True)

columns = list(dfho.columns)
tree_ho =ttk.Treeview(self,height=10,show='headings',columns=columns)	
tree_ho.grid(column=5,row=20,columnspan=8,rowspan=10,sticky='n,e,w,s')
ys = ttk.Scrollbar(self, orient = 'vertical', command = tree_ho.yview)		
tree_ho['yscrollcommand'] = ys.set													
ys.grid(column =14, row = 20, sticky = 'n,w,s',rowspan=10)
for name in columns:
	tree_ho.column(name,width=30,anchor='w')
	tree_ho.heading(name,text=name)

for index,rowinfo in dfho.iterrows():
			tree_ho.insert('',index,values = list(rowinfo)) # index 默认'end'
			tree_逆写.insert('',0,values = list(rowinfo)) #逆序写入,index 改成0

 # (功能)列排序命令
def tree_sort_column(tv,col,reverse):
	l=[(tv.set(k,col),k) for k in tv.get_children('')]
	l.sort(reverse=reverse)
	for index,(val,k) in enumerate(l):
		tv.move(k,'',index)
	tv.heading(col,command=lambda:tree_sort_column(tv,col,not reverse))
# (触发)绑定列排序的触发
for col in columns:  
	tree_ho.heading(col, text=col, command=lambda _col=col: tree_sort_column(tree_ho, _col, False))

【module】requests

page = requests.get('http://hq.sinajs.cn/?format=text&list=sh600519')
stock_info = page.text
mt_info = stock_info.split(',')

page = requests.get('http://data.eastmoney.com/other/index/hs300.html')
stock_info = page.text

【module】akshare

import akshare as ak
# 个股日数据
def get_codeData(code='sh600519'):
			   df = ak.stock_zh_a_daily(symbol=code, start_date="20201203", end_date="20210115",adjust="qfq")
			   df.to_excel("D:\\Python\\002\\贵州茅台k.xlsx")
# 个股分时数据
stock_zh_a_minute_df = ak.stock_zh_a_minute(symbol='sh000300', period='1')
(period='1'; 获取 1, 5, 15, 30, 60 分钟的数据频率)
# 基金日数据
df = ak.fund_etf_hist_sina(symbol=ttcode)
# 基金分时数据

# 期货分时数据
ak.futures_zh_minute_sina(symbol="TF2009", period="1")
# 中国宏观-海关进出口增减情况
ak.macro_china_hgjck()
# 获取新浪财经-财务报表-三大报表
ak.stock_financial_report_sina(stock="600004", symbol="现金流量表")



股票数据
ak.stock_info_a_code_name()													A 股股票代码和简称
ak.stock_zh_a_cdr_daily(symbol='sh600519')									CDR历史行情数据
ak.stock_a_lg_indicator(stock="000001")										A股个股市盈率、市净率和股息率
ak.stock_em_hsgt_board_rank(symbol="北向资金增持行业板块排行", indicator="今日")	沪深港通板块排行
ak.stock_sector_spot(indicator="新浪行业")	

中国宏观


全球指数
ak.index_investing_global(country="美国", index_name="VIX恐慌指数", period="每月", start_date="2005-01-01", end_date="2020-06-05")

df=ak.stock_em_hsgt_north_cash(indicator="沪股通")	//三选一 ("沪股通", "深股通", "北上")
"stock_em_hsgt_north_net_flow_in"  		# 沪深港通北向-净流入
"stock_em_hsgt_north_cash"  			# 沪深港通北向-资金余额
"stock_em_hsgt_north_acc_flow_in"  		# 沪深港通北向-累计净流入
"stock_em_hsgt_south_net_flow_in"  		# 沪深港通南向-净流入
"stock_em_hsgt_south_cash"  			# 沪深港通南向-资金余额
"stock_em_hsgt_south_acc_flow_in"       # 沪深港通南向-累计净流入

【module】datetime

方法:日期模块的应用
方法:各种写法

import time
import datetime
from datetime import date
# 创建日期
date= datetime.date(year, month, day)

# 秒计时
_a = time.time()
_b = time.time()
print('Time used:xxx'.ljust(49,'.')+str(round(_b-_a,1)).rjust(7)) 

print('Draw_tick'.center(49,'='))
Regex = re.compile(r'\d\d\d\d-\d\d-\d\d')
print('data_1m start:'.ljust(18,'.') +Regex.findall(str(data_1m['day'][0:0+1]))[0])

# 日期、时间戳、字符串
1#把datetime转成字符串:   dt.strftime("%Y-%m-%d")
2#把字符串转成datetime:   datetime.strptime( string, "%Y-%m-%d")
3#把字符串转成时间戳形式:  先转化成datetime   time.mktime( datetime.strptime( string, "%Y-%m-%d").timetuple())
4#把时间戳转成字符串形式:  time.strftime("%Y-%m-%d", tiem.localtime( stamp))
5#把datetime类型转外时间戳形式:   time.mktime( dateTim.timetuple())

# 今天格式
[date = datetime.date(y,m,d)]
[datetime = datetime.datetime(y,m,d,h,m)]
today=datetime.date.today()
today=datetime.datetime(datetime.datetime.now().year,datetime.datetime.now().month,datetime.datetime.now().day)
date = datetime.datetime.strptime(date_str, '%Y/%m/%d')			文字转日期
date.weekday(d日期)												0:星期一
d.isocalendar()  return(year, week number, weekday)				返回(年,第几周,周几)

datetime.datetime.strptime										字符串转日期
datetime.datetime.strftime 										日期转字符串
date.strftime("%Y%m%d")										当天日期转字符串"20210302"
datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")			当天日期转字符串“2021-03-02  10:08:44”
datetime.datetime.strptime(strdatetime, "%Y-%m-%d %H:%M:%S")	指定日期转字符串

# 日期的加减
comdate=today+datetime.timedelta(days=-(int(a)))
* timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
(date1 - date2).days    										日期delta转int
# 分时比较
if datetime.time(7, 00) < datetime.datetime.now().time() < datetime.time(19,00):
# 辅助-常见日期string 转datetime
def s2d(st):  				#'1900-01-01';'19000101';'1900.1.1' 仅年月日顺序适用
	if 8==len(st) and 0 == st.count('-') and 0 == st.count('.') and 0 == st.count('——'):
		date = datetime.datetime(int(st[:4]),int(st[4:6]),int(st[6:8]),0,0)
	else:
		Regex = re.compile(r'(\d\d\d\d)\D*(\d\d|\d)\D*(\d\d|\d)')
		mo=Regex.findall(st)
		date = datetime.datetime(int(mo[0][0]),int(mo[0][1]),int(mo[0][2]),0,0)
	return date



【module】calendar
使用介绍

calendar.setfirstweekday(firstweekday=6)					将星期日设置为一周第一天
calendar.firstweekday()										返回一周的第一天,0是星期一,…,6为星期日
calendar.isleap(2018)										判断指定是否是闰年,闰年为True,平年为False
calendar.leapdays(2008, 2011)		返回y1与y2年份之间的闰年数量,y1与y2皆为年份。包括起始年,不包括结束年
calendar.weekday(2018, 8, 8)								获取指定日期为星期几
calendar.weekheader(4)										返回包含星期的英文缩写,n表示英文缩写所占的宽度
	Mon  Tue  Wed  Thu  Fri  Sat  Sun 
monthrange(year, month)  " (2, 31)"	//星期三 31天			返回一个由一个月第一个天的星期与当前月的天数组成的元组
monthcalendar(year, month) ""[[0, 1, 2, 3, 4, 5, 6],..."
##打印日历
prmonth(theyear, themonth, w=0, l=0) //
calendar.prmonth(2018, 8) 										打印一个月的日历
calendar.month(2018, 8)											返回一个月的日历的多行文本字符串
prcal(year, w=0, l=0, c=6, m=3):打印一年的日历,w每个单元格宽度,默认0,内部已做处理,最小宽度为2,l每列换l行,默认为0,内部已做处理,至少换行1行,c表示月与月之间的间隔宽度,默认为6,内部已做处理,最小宽度为2,m表示将12个月分为m列
calendar.prcal(2018, m=4)										打印一年的日历
calendar.calendar(2018, m=4)									以多行字符串形式返回一年的日历

【进度条参考案例】

Print 同一行打印显示进度条效果

import sys,time
 
total = 153
 
for i in range(total):
 
	if i+1 == total:
		percent = 100.0
		print('当前核算进度 : %s [%d/%d]'%(str(percent)+'%',i+1,total),end='\n')
	else:
		percent = round(1.0 * i / total * 100,2)
		print('当前核算进度 : %s [%d/%d]'%(str(percent)+'%',i+1,total),end='\r')
	time.sleep(0.01)

进度条效果

import time
for i in range(1,20):
    print("█" * i + "%*.*s" %(42-2*i,5,int(i * 100 / 19)) + "%", end='\r')
    time.sleep(1)
print("\n")
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值