文章目录
- Combobox绑定事件
- 互相调用
- 源代码
Python绘图系统:
- 📈从0开始实现一个三维绘图系统
- 自定义控件:坐标设置控件📉坐标列表控件📉支持多组数据的绘图系统
- 图表类型和风格:散点图和条形图📊混合类型图表
Combobox绑定事件
DrawType类可以设置绘图维度,而绘图维度和坐标轴的个数是息息相关的。换言之,一个比较合理的交互逻辑是,改选DrawType的维度后,就应该可以改变坐标轴的个数。为了实现这个功能,需要为ComboBox绑定一个事件,改动起来非常简单,只需在initWidgets最后加上一行就可以。
def initWidgets(self, ws):
if ws==None: ws = [8, 3]
slct = ttk.Combobox(self, width=ws[0], textvariable=self.drawType)
slct['value'] = self.types
slct.pack(side=tk.LEFT)
slct = ttk.Combobox(self, width=ws[1], textvariable=self.drawDim)
slct['value'] = self.dims
slct.pack(side=tk.LEFT)
slct.bind('<<ComboboxSelected>>', self.dimChanged)
接下来比较重要的则是self.dimChanged的定义。由于我们希望当Combobox改变时,是另一个控件的内容发生变化,所以self.dimChanged最好是其他控件传入的一个函数。故而需要更改DrawType的初始化函数,即添加一个func参数,然后把这个参数赋给self.dimChanged方法。
def __init__(self, master, types, slctType,
slctDim="3", ws=None, func=None, **options):
super().__init__(master, **options)
#。。。
self.dimChanged = func
# 。。。
互相调用
最后,修改AxisList中初始化DrawType的语句
self.drawTypeDim = DrawType(frm, types, slctType, func=self.dimChanged)
并创建self.dimChanged函数,代码如下,逻辑是根据当前选择的维度来更新txyz这几个AxisFrame。
def dimChanged(self, evt):
txyz = self.getDrawDim()
for flag in 'txyz':
self.vis[flag] = flag in txyz
self.updateVisible()
def updateVisible(self):
for flag in 'txyz':
self.afs[flag].pack_forget()
for flag in 'txyz':
if self.vis[flag]:
self.afs[flag].pack(side=tk.TOP, fill=tk.X)
效果如下
最后的最后,在坐标轴创建时也应该遵循绘图维度和坐标个数之间的关系,这样打开软件或者新创建一组坐标的时候,就可以自动与绘图维度相匹配了。
def initAxis(self, mode, widths):
for flag in 'txyz':
self.afs[flag] = AxisFrame(self._c, flag, mode, widths)
self.afs[flag].pack(side=tk.TOP, fill=tk.X)
self.vis = {L : L in self.getDrawDim() for L in 'txyz'}
self.updateVisible()
源代码
import tkinter as tk
import tkinter.ttk as ttk
from tkinter.filedialog import askopenfilename
import matplotlib as mpl
mpl.use('TkAgg')
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.figure import Figure
import numpy as np
class AxisFrame(ttk.Frame):
# widths 是每个控件的宽度
def __init__(self, master, label, mode, widths, **options):
super().__init__(master, **options)
self.pack()
self.label = label
self.initVar(mode)
self.initWidgets(widths)
def initVar(self, mode):
self.MODES = ("序列化", "源代码", "外部导入", "无数据")
self.mode = tk.StringVar()
self.setMode(mode)
def initWidgets(self, widths):
tk.Label(self, text=self.label, width=widths[0]).pack(side=tk.LEFT)
self.slct = ttk.Combobox(self, width=widths[1], textvariable=self.mode)
self.slct['value'] = self.MODES
self.slct.pack(side=tk.LEFT)
self.entry = tk.Entry(self, width=widths[2])
self.entry.pack(padx=5, side=tk.LEFT, fill=tk.X)
def setText(self, text):
self.entry.delete(0, "end")
self.entry.insert(0, text)
def get(self):
return self.entry.get()
def setMode(self, mode):
if type(mode) != str:
mode = self.MODES[mode]
self.mode.set(mode)
def setData(self, data=None, **txyz):
if self.mode.get() == "序列化":
return self.getArray()
elif self.mode.get() == "外部导入":
return self.loadData(data)
else:
return self.readPython(**txyz)
def readPython(self, t=None, x=None, y=None, z=None):
self.data = eval(self.get())
return self.data
def loadData(self, data):
if type(data) != type(None):
self.data = data
return self.data
def getArray(self):
val = self.get()
self.data = eval(f"np.linspace({val})")
return self.data
class AxisList(ttk.Frame):
def __init__(self, master,
title, mode, widths,
types, slctType, # 绘图类型Combobox的参数
**options):
super().__init__(master, **options)
self.pack()
self.afs = {}
self.data = {}
self.initWidgets(title, widths)
self.initFeature(types, slctType)
self.initAxis(mode, widths)
def initWidgets(self, title, widths):
self.btn = ttk.Button(self, text=title, width=sum(widths)+5,
command=self.Click)
self.btn.pack(side=tk.TOP, fill=tk.X, expand=tk.YES)
self._c = ttk.Frame(self)
self.collapsed = True
self.Click()
def initFeature(self, types, slctType):
frm = ttk.Frame(self._c)
frm.pack(pady=2, side=tk.TOP, fill=tk.X)
ttk.Button(frm, text="加载",width=5,
command=self.btnLoadData).pack(side=tk.LEFT)
frm = ttk.Frame(self._c)
frm.pack(pady=2, side=tk.TOP, fill=tk.X)
self.drawTypeDim = DrawType(frm, types, slctType,
func=self.dimChanged)
self.drawTypeDim.pack(side=tk.LEFT)
self.vis = {L : True for L in 'txyz'}
for flag in 'txyz':
btn = ttk.Button(frm, text=flag, width=3)
btn.pack(side=tk.LEFT)
btn.bind("<Button-1>", self.btnAxisCollapse)
def dimChanged(self, evt):
txyz = self.getDrawDim()
for flag in 'txyz':
self.vis[flag] = flag in txyz
self.updateVisible()
def updateVisible(self):
for flag in 'txyz':
self.afs[flag].pack_forget()
for flag in 'txyz':
if self.vis[flag]:
self.afs[flag].pack(side=tk.TOP, fill=tk.X)
def getDrawType(self):
return self.drawTypeDim.getType()
def getDrawDim(self):
return self.drawTypeDim.getDim()
def initAxis(self, mode, widths):
for flag in 'txyz':
self.afs[flag] = AxisFrame(self._c, flag, mode, widths)
self.afs[flag].pack(side=tk.TOP, fill=tk.X)
self.vis = {L : L in self.getDrawDim() for L in 'txyz'}
self.updateVisible()
def btnAxisCollapse(self, evt):
flag = evt.widget['text']
self.vis[flag] = not self.vis[flag]
self.updateVisible()
def btnLoadData(self):
name = askopenfilename()
data = np.genfromtxt(name)
for i, flag in enumerate('xyz'):
if i >= data.shape[1]:
return
self.setOneMode(flag, "外部导入")
self.data[flag] = self.setData(flag, data[:,i])
def Click(self):
if self.collapsed:
self._c.pack(side=tk.TOP, fill=tk.BOTH, expand=tk.YES)
else:
self._c.pack_forget()
self.collapsed = not self.collapsed
def setData(self, flag, data=None, **options):
return self.afs[flag].setData(data, **options)
def setOneMode(self, flag, mode):
self.afs[flag].setMode(mode)
# 绘图类型和维度
class DrawType(ttk.Frame):
# ws为两个combobox的宽
def __init__(self, master, types, slctType,
slctDim="3", ws=None, func=None, **options):
super().__init__(master, **options)
self.pack()
self.types = types # 绘图类型
self.dims = ("1", "2", "3", "1+1", "2+1", "3+1") # 绘图维度
self.dimChanged = func
self.initVar(slctType, slctDim)
self.initWidgets(ws)
def initVar(self, slctType, dim):
self.drawType = tk.StringVar()
self.drawType.set(slctType)
self.drawDim = tk.StringVar()
if type(dim) != str:
dim = self.dims[int(dim)]
self.drawDim.set(dim)
def initWidgets(self, ws):
if ws==None: ws = [8, 3]
slct = ttk.Combobox(self, width=ws[0], textvariable=self.drawType)
slct['value'] = self.types
slct.pack(side=tk.LEFT)
slct = ttk.Combobox(self, width=ws[1], textvariable=self.drawDim)
slct['value'] = self.dims
slct.pack(side=tk.LEFT)
slct.bind('<<ComboboxSelected>>', self.dimChanged)
def getType(self):
return self.drawType.get()
def getDim(self):
dim = self.drawDim.get()
dimDct = {"1" : "x", "2" : "xy", "3" : "xyz",
"1+1": "tx", "2+1": "txy", "3+1": "txyz"}
return dimDct[dim]
class DarwSystem():
def __init__(self):
self.root = tk.Tk()
self.root.title("数据展示工具")
self.data = {}
self.als = []
self.initConst()
self.setFrmCtrl()
frmFig = ttk.Frame(self.root)
frmFig.pack(side=tk.LEFT,fill=tk.BOTH,expand=tk.YES)
self.setFrmFig(frmFig)
self.root.mainloop()
def initConst(self):
self.TYPES = ("点线图", "散点图", "条形图")
self.drawDct = {
"点线图" : self.drawPlot,
"散点图" : self.drawScatter,
"条形图" : self.drawBar
}
def setFrmCtrl(self):
frmCtrl = ttk.Frame(self.root,width=320)
frmCtrl.pack(side=tk.RIGHT, fill=tk.Y)
frm = ttk.Frame(frmCtrl, width=320)
frm.pack(side=tk.TOP, fill=tk.X)
self.setCtrlButtons(frm)
self.frmAxis = ttk.Frame(frmCtrl)
self.frmAxis.pack(side=tk.TOP, fill=tk.X)
self.addLast(None)
# ! 工具栏
def setCtrlButtons(self, frm):
self.drawTypeDim = DrawType(frm, self.TYPES, "点线图")
self.drawTypeDim.pack(side=tk.LEFT)
ttk.Button(frm, text="绘图",width=5,
command=self.btnDrawImg).pack(side=tk.LEFT)
ttk.Button(frm, text="加载",width=5,
command=self.btnLoadData).pack(side=tk.LEFT)
btn = ttk.Button(frm, text="+", width=3)
btn.pack(side=tk.LEFT)
btn.bind("<Button-1>", self.addLast)
btn = ttk.Button(frm, text="-", width=3)
btn.pack(side=tk.LEFT)
btn.bind("<Button-1>", self.deleteLast)
def addLast(self, evt):
title = f"坐标{len(self.als)}"
al = AxisList(self.frmAxis, title, 1, [5,10,20],
self.TYPES, self.drawTypeDim.getType())
al.pack(side=tk.TOP, fill=tk.X)
self.als.append(al)
def deleteLast(self, evt):
self.als[-1].pack_forget()
del self.als[-1]
def btnLoadData(self):
name = askopenfilename()
data = np.genfromtxt(name)
for i, flag in enumerate('xyz'):
if i >= data.shape[1]:
return
self.AL.setOneMode(flag, "外部导入")
self.data[flag] = self.AL.setData(flag, data[:,i])
def readDatas(self, al):
dct = {}
data = {}
for flag in 'xyz':
data[flag] = al.setData(flag, **dct)
dct[flag] = data[flag]
return data
def btnDrawImg(self):
self.fig.clf()
keys = self.drawTypeDim.getDim()
p = '3d' if 'z' in keys else None
ax = self.fig.add_subplot(projection=p)
for al in self.als:
data = self.readDatas(al)
draw = self.drawDct[al.getDrawType()]
draw(ax, data, keys)
self.fig.subplots_adjust(left=0.1, right=0.95, top=0.95, bottom=0.08)
self.canvas.draw()
def drawBar(self, ax, data, keys):
ax.bar(data['x'], data['y'])
def drawPlot(self, ax, data, keys):
ax.plot(*[data[key] for key in keys])
def drawScatter(self, ax, data, keys):
ax.scatter(*[data[key] for key in keys])
def setFrmFig(self, frmFig):
self.fig = Figure()
self.canvas = FigureCanvasTkAgg(self.fig,frmFig)
self.canvas.get_tk_widget().pack(
side=tk.TOP,fill=tk.BOTH,expand=tk.YES)
self.toolbar = NavigationToolbar2Tk(self.canvas,frmFig,
pack_toolbar=False)
self.toolbar.update()
self.toolbar.pack(side=tk.RIGHT)
if __name__ == "__main__":
test = DarwSystem()