pygui_simple 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,112 @@
1
+ # !/usr/bin/python3
2
+ # -*- coding: UTF-8 -*-
3
+ from typing import Any, override
4
+ import tkinter as tk
5
+
6
+ from pygui.winbasic import Control
7
+
8
+
9
+ class tkControl(Control):
10
+ def __init__(self, parent: tk.Misc, title: str, idself: str, tkctrl: tk.Widget):
11
+ super().__init__(title, idself)
12
+ self._parent: tk.Misc = parent
13
+ self._tkctrl: tk.Widget = tkctrl
14
+ self._assemble_type: str = ""
15
+ self._layout_info: tk._PackInfo | tk._PlaceInfo | None = None
16
+ # self._hidden: bool = True
17
+
18
+ @property
19
+ def control(self):
20
+ return self._tkctrl
21
+
22
+ @property
23
+ def visible(self):
24
+ return self._tkctrl.winfo_viewable()
25
+
26
+ @override
27
+ def configure(self, **kwargs: Any):
28
+ self._tkctrl.configure(**kwargs)
29
+
30
+ @override
31
+ def __getitem__(self, item: str):
32
+ # return getattr(self._tkctrl, item)
33
+ return self._tkctrl[item]
34
+
35
+ @override
36
+ def __setitem__(self, item: str, value):
37
+ self._tkctrl.__setitem__(item, value)
38
+
39
+ @override
40
+ def disable(self, is_disbl: bool = True):
41
+ if is_disbl:
42
+ self._tkctrl.configure(state="disabled")
43
+ else:
44
+ self._tkctrl.configure(state="normal")
45
+
46
+ def _get_layout_method(self, widget: tk.Widget):
47
+ """ Determine the layout manager used by the widget (pack/grid/place)"""
48
+ try:
49
+ # Check if place layout is used
50
+ if widget.tk.call("place", "info", widget):
51
+ return "place"
52
+ except tk.TclError as _:
53
+ # print(f"{self._idself}._get_layout_method.place: {e}")
54
+ pass
55
+ try:
56
+ # Check if pack layout is used
57
+ if widget.tk.call("pack", "info", widget):
58
+ return "pack"
59
+ except tk.TclError as _:
60
+ # print(f"{self._idself}._get_layout_method.pack: {e}")
61
+ pass
62
+ try:
63
+ # Check if grid layout is used
64
+ if widget.tk.call("grid", "info", widget):
65
+ return "grid"
66
+ except tk.TclError as _:
67
+ # print(f"{self._idself}._get_layout_method.grid: {e}")
68
+ pass
69
+
70
+ raise ValueError("No layout manager is used")
71
+
72
+ @override
73
+ def hide(self, is_hide: bool = True):
74
+ if not self._assemble_type:
75
+ self._assemble_type = self._get_layout_method(self._tkctrl)
76
+ match self._assemble_type:
77
+ case "grid":
78
+ if is_hide:
79
+ self._tkctrl.grid_remove()
80
+ else:
81
+ self._tkctrl.grid()
82
+ case "pack":
83
+ if is_hide:
84
+ # if not self._hidden:
85
+ try:
86
+ self._layout_info = self._tkctrl.pack_info()
87
+ self._tkctrl.pack_forget()
88
+ except Exception as _:
89
+ # print(f"{self._idself}.hide.pack: {e}")
90
+ pass
91
+ else:
92
+ # if self._hidden:
93
+ assert self._layout_info is not None
94
+ self._tkctrl.pack(**self._layout_info)
95
+ case "place":
96
+ if is_hide:
97
+ try:
98
+ self._layout_info = self._tkctrl.place_info()
99
+ self._tkctrl.place_forget()
100
+ except Exception as _:
101
+ # print(f"{self._idself}.hide.place: {e}")
102
+ pass
103
+ else:
104
+ assert self._layout_info is not None
105
+ self._tkctrl.place(**self._layout_info)
106
+ case _:
107
+ raise ValueError(f"unkown layout: {self._assemble_type}")
108
+ # self._hidden = is_hide
109
+
110
+ @override
111
+ def destroy(self):
112
+ self._tkctrl.destroy()
@@ -0,0 +1,294 @@
1
+ # !/usr/bin/python3
2
+ # -*- coding: UTF-8 -*-
3
+ from dataclasses import dataclass, field
4
+ import tkinter as tk
5
+ from typing import cast, Any
6
+
7
+ from matplotlib.figure import Figure
8
+ from matplotlib.lines import Line2D
9
+ from matplotlib.container import Container
10
+ from matplotlib.axes._axes import Axes
11
+ import matplotlib.pyplot as plt
12
+ from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
13
+ from numpy.typing import ArrayLike
14
+ import numpy as np
15
+
16
+ from pygui.tkcontrol import tkControl
17
+
18
+
19
+ __version__ = "2.4.0"
20
+
21
+
22
+ font = {'family' : 'SimHei',
23
+ 'weight' : 'bold',
24
+ 'size' : '16'}
25
+ plt.rc('font', **font) # 步骤一(设置字体的更多属性)
26
+ plt.rc('axes', unicode_minus=False) # 步骤二(解决坐标轴负数的负号显示问题)
27
+
28
+
29
+ @dataclass
30
+ class LineData:
31
+ ydata: ArrayLike # np.ndarray / list
32
+ style_dict: dict[str, object] = field(default_factory=dict)
33
+ typ: str = "line"
34
+ visible: bool = True
35
+ line: Line2D | Container | None = None
36
+
37
+
38
+ class MatPlotCtrl(tkControl):
39
+ def __init__(
40
+ self,
41
+ parent: tk.Misc,
42
+ idself: str,
43
+ title: str = "",
44
+ xlabel: str = "",
45
+ ylabel: str = "",
46
+ size: tuple[float, float] = (640, 480),
47
+ ):
48
+ self._dpi: float = 80
49
+ self._xdata: ArrayLike = []
50
+ self._linedata_list: list[LineData] = []
51
+
52
+ self._xmin: float = float("inf")
53
+ self._xmax: float = float("-inf")
54
+ self._ymin: float = float("inf")
55
+ self._ymax: float = float("-inf")
56
+
57
+ self._size: tuple[float, float] = cast(tuple[float, float], tuple(item / self._dpi for item in size))
58
+ # print(f"size = {self._size}")
59
+
60
+ self._title: str = title
61
+ self._xlabel: str = xlabel
62
+ self._ylabel: str = ylabel
63
+
64
+ fig: Figure = Figure(figsize=self._size, dpi=self._dpi)
65
+ self._canvas: FigureCanvasTkAgg = FigureCanvasTkAgg(fig, parent)
66
+ super().__init__(parent, title, idself, self._canvas.get_tk_widget())
67
+ self._ax: Axes = fig.add_subplot()
68
+ fig.subplots_adjust(bottom=0.25)
69
+ self._create()
70
+
71
+ def _create(self):
72
+ _ = self._ax.set_title(self._title)
73
+ _ = self._ax.set_xlabel(self._xlabel)
74
+ _ = self._ax.set_ylabel(self._ylabel)
75
+ self._ax.grid()
76
+ # self._ax.legend(loc='upper right')
77
+ self._ax.autoscale()
78
+
79
+ @property
80
+ def xdata(self):
81
+ return self._xdata
82
+
83
+ @xdata.setter
84
+ def xdata(self, xdata: ArrayLike):
85
+ self._xdata = xdata
86
+
87
+ def _bar(self, xdata: ArrayLike, ydata: ArrayLike, **style_dict: Any):
88
+ bar = self._ax.bar(xdata, ydata, **style_dict)
89
+ if isinstance(bar, list):
90
+ return bar[0]
91
+ else:
92
+ return bar
93
+
94
+ def _plot(self, xdata: ArrayLike, ydata: ArrayLike, **style_dict: Any):
95
+ line = self._ax.plot(xdata, ydata, **style_dict)
96
+ if isinstance(line, list):
97
+ return line[0]
98
+ else:
99
+ return line
100
+
101
+ def _draw(self, xdata: ArrayLike, ydata: ArrayLike, typ: str, **style_dict: Any):
102
+ match typ:
103
+ case "line":
104
+ line = self._plot(self._xdata, ydata, **style_dict)
105
+ case "bar":
106
+ line = self._bar(self._xdata, ydata, **style_dict)
107
+ case _:
108
+ raise ValueError(f"don't support type: {typ}")
109
+ return line
110
+
111
+ def add_line(self, line_data: LineData):
112
+ ydata = line_data.ydata
113
+ if line_data.visible:
114
+ line_data.line = self._draw(self._xdata, ydata, line_data.typ,
115
+ **line_data.style_dict)
116
+
117
+ self._linedata_list.append(line_data)
118
+
119
+ return len(self._linedata_list) - 1
120
+
121
+ def update_ydata(self, idx: int, ydata: ArrayLike):
122
+ self._linedata_list[idx].ydata = ydata
123
+ if self._linedata_list[idx].visible:
124
+ cast(Line2D, self._linedata_list[idx].line).set_ydata(ydata)
125
+
126
+ def show_line(self, idx: int, is_show: bool):
127
+ line_data = self._linedata_list[idx]
128
+ line_data.visible = is_show
129
+ line = line_data.line
130
+ # pv(line)
131
+ if is_show:
132
+ if not line:
133
+ line_data.line = self._draw(
134
+ self._xdata, line_data.ydata, line_data.typ,
135
+ **line_data.style_dict
136
+ )
137
+ else:
138
+ if line_data.line is not None:
139
+ line_data.line.remove()
140
+ del line_data.line
141
+ line_data.line = None
142
+
143
+ def _recalculate_axes_scale(self):
144
+ self._ymin = float("inf")
145
+ self._ymax = float("-inf")
146
+
147
+ for line in self._linedata_list:
148
+ if line.visible:
149
+ ydata = line.ydata
150
+ # pv(type(ydata))
151
+ try:
152
+ ymin = min(ydata)
153
+ ymax = max(ydata)
154
+ except ValueError:
155
+ ymin = ydata.min()
156
+ ymax = ydata.max()
157
+
158
+ self._ymin = min(self._ymin, ymin)
159
+ self._ymax = max(self._ymax, ymax)
160
+
161
+ self._ymin = 0 if self._ymin >= 0 else self._ymin
162
+ _ = self._ax.set_ylim(self._ymin * 1.05, self._ymax * 1.1)
163
+
164
+ self._xmin = float("inf")
165
+ self._xmax = float("-inf")
166
+
167
+ try:
168
+ xmin = min(self._xdata)
169
+ xmax = max(self._xdata)
170
+ except ValueError:
171
+ xmin = self._xdata.min()
172
+ xmax = self._xdata.max()
173
+ # finally:
174
+ # pass
175
+
176
+ self._xmin = min(self._xmin, xmin)
177
+ self._xmax = max(self._xmax, xmax)
178
+
179
+ self._xmin = -0.15 if self._xmin == 0 else self._xmin
180
+ _ = self._ax.set_xlim(self._xmin * 1.05, self._xmax * 1.05)
181
+
182
+ def clear_canvas(self):
183
+ """_summary_
184
+ it will remove grid line, do we need to preserve it?
185
+ """
186
+ self._ax.cla() # plt.cla()
187
+ # fig.clf() # plt.clf()
188
+ self._create()
189
+ self._linedata_list.clear()
190
+
191
+ def draw(self):
192
+ self._recalculate_axes_scale()
193
+ _, labels = self._ax.get_legend_handles_labels()
194
+ if len(labels) >= 1:
195
+ _ = self._ax.legend(loc="upper right")
196
+ self._canvas.draw()
197
+
198
+
199
+ class Plot:
200
+ def __init__(self, title: str = "", num_row: int = 1, num_col: int = 1, **plot_dict: Any):
201
+ self._title: str = title
202
+ fig, axs = plt.subplots(num_row, num_col, **plot_dict)
203
+ self._fig: Figure = fig
204
+ self._axes: list[Axes] = []
205
+ try:
206
+ self._axes = axs.flat
207
+ except:
208
+ self._axes = [axs]
209
+ self._i: int = -1
210
+
211
+ def add_subplot(self, title: str, xlabel: str = "",
212
+ ylabel: str = "", plot_num: int | None = None):
213
+ if plot_num is not None:
214
+ self._i = plot_num
215
+ else:
216
+ self._i += 1
217
+ ax = self._axes[self._i]
218
+
219
+ _ = ax.set_xlabel(xlabel)
220
+ _ = ax.set_ylabel(ylabel)
221
+ _ = ax.set_title(title)
222
+
223
+ return ax
224
+
225
+ def set_axes(self, plot_num: int = 0, **axes_dict):
226
+ ax = self._axes[plot_num]
227
+ _ = ax.set(**axes_dict)
228
+ return ax
229
+
230
+ def add_line(self, ax: Axes, xdata: ArrayLike, ydata: ArrayLike, typ: str = "line",
231
+ **style_dict):
232
+ match typ:
233
+ case "line":
234
+ _, = ax.plot(xdata, ydata, **style_dict)
235
+ case "bar":
236
+ _, = ax.bar(xdata, ydata, **style_dict)
237
+ case _:
238
+ raise ValueError(f"don't support type: {typ}")
239
+
240
+ def draw(self):
241
+ # plt.suptitle(self._title)
242
+ plt.subplots_adjust(hspace=0.5, wspace=0.5)
243
+
244
+ for ax in self._axes:
245
+ # pv(ax.get_legend())
246
+ _, labels = ax.get_legend_handles_labels()
247
+ if len(labels) >= 1:
248
+ _ = ax.legend(loc="upper right")
249
+ plt.show()
250
+
251
+
252
+ if __name__ == "__main__":
253
+
254
+ import numpy as np
255
+
256
+ # np.seterr(divide="ignore", invalid="ignore")
257
+
258
+ root = tk.Tk()
259
+ root.title("MatPlot Example")
260
+ # 调整窗口大小并居中
261
+ screen_width, screen_height = root.maxsize() # 获取屏幕最大长宽
262
+ w, h = 480, 240
263
+ x = int((screen_width-w)/2)
264
+ y = int((screen_height-h)/2)
265
+ root.geometry(f'{w}x{h}+{x}+{y}') # 设置窗口大小,调整位置
266
+ # root.resizable(width=False, height=False) # False表示不可以缩放,True表示可以缩放
267
+
268
+ # plot_example = Plot("Mesh Grid")
269
+ mat_plot_example = MatPlotCtrl(root, "Mesh Grid")
270
+ mat_plot_example.pack(
271
+ side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(10, 10), pady=(10, 10)
272
+ )
273
+
274
+ menubar = tk.Menu(root)
275
+
276
+ file_menu = tk.Menu(menubar, tearoff=False)
277
+ file_menu.add_command(label="...")
278
+ file_menu.add_separator()
279
+ file_menu.add_command(label="Exit", command=root.destroy)
280
+ menubar.add_cascade(label="File", menu=file_menu)
281
+
282
+ _= root.config(menu=menubar)
283
+
284
+ x = np.array(
285
+ [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
286
+ )
287
+ mat_plot_example.xdata = x
288
+ y = np.array([[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]])
289
+ line_dict = {"label": "haha", "marker": ".", "markersize": 10, "linestyle": "-."}
290
+ linedata = LineData(y, line_dict)
291
+ idx = mat_plot_example.add_line(linedata)
292
+ mat_plot_example.draw()
293
+
294
+ root.mainloop()