1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
| import sys from datetime import datetime
import pandas as pd from PIL import Image, ImageDraw, ImageFont from PySide6.QtCore import QDate, QPoint, Qt from PySide6.QtGui import QAction from PySide6.QtWidgets import ( QAbstractItemView, QApplication, QDateEdit, QFileDialog, QHBoxLayout, QHeaderView, QLabel, QLineEdit, QMainWindow, QMenu, QMessageBox, QPushButton, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, )
class TimelineGenerator(QMainWindow): def __init__(self): super().__init__() self.initUI()
def initUI(self): self.setWindowTitle("时间表生成器") self.setGeometry(100, 100, 1200, 800)
central_widget = QWidget() self.setCentralWidget(central_widget) layout = QVBoxLayout(central_widget)
title_layout = QHBoxLayout() title_layout.addWidget(QLabel("图表标题:")) self.title_input = QLineEdit("时间表") self.title_input.setMinimumWidth(300) title_layout.addWidget(self.title_input) title_layout.addStretch() layout.addLayout(title_layout)
self.table = QTableWidget() self.table.setColumnCount(3) self.table.setHorizontalHeaderLabels(["名称", "开始日期", "结束日期"]) self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) self.table.setContextMenuPolicy(Qt.CustomContextMenu) self.table.customContextMenuRequested.connect(self.show_context_menu) self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.init_sample_data() layout.addWidget(self.table)
self.generate_btn = QPushButton("生成图片") self.generate_btn.clicked.connect(self.generate_image) self.generate_btn.setMinimumHeight(40) layout.addWidget(self.generate_btn)
def init_sample_data(self): """初始化数据""" sample_data = []
self.table.setRowCount(len(sample_data)) for i, (name, start, end) in enumerate(sample_data): self.table.setItem(i, 0, QTableWidgetItem(name))
start_date = QDateEdit() start_date.setDate(QDate.fromString(start, "yyyy-MM-dd")) start_date.setCalendarPopup(True) start_date.setDisplayFormat("yyyy-MM-dd") self.table.setCellWidget(i, 1, start_date)
end_date = QDateEdit() end_date.setDate(QDate.fromString(end, "yyyy-MM-dd")) end_date.setCalendarPopup(True) end_date.setDisplayFormat("yyyy-MM-dd") self.table.setCellWidget(i, 2, end_date)
def show_context_menu(self, position: QPoint): """显示右键菜单""" menu = QMenu(self)
insert_above_action = QAction("在上方插入行", self) insert_above_action.triggered.connect(lambda: self.insert_row_above()) menu.addAction(insert_above_action)
insert_below_action = QAction("在下方插入行", self) insert_below_action.triggered.connect(lambda: self.insert_row_below()) menu.addAction(insert_below_action)
menu.addSeparator()
delete_action = QAction("删除行", self) delete_action.triggered.connect(self.delete_row) menu.addAction(delete_action)
menu.exec(self.table.viewport().mapToGlobal(position))
def insert_row_above(self): """在选中行上方插入新行""" current_row = self.table.currentRow() if current_row < 0: current_row = 0 self.insert_row(current_row)
def insert_row_below(self): """在选中行下方插入新行""" current_row = self.table.currentRow() if current_row < 0: current_row = self.table.rowCount() - 1 self.insert_row(current_row + 1)
def insert_row(self, row: int): """在指定位置插入新行""" self.table.insertRow(row)
today = QDate.currentDate()
self.table.setItem(row, 0, QTableWidgetItem(""))
start_date = QDateEdit() start_date.setDate(today) start_date.setCalendarPopup(True) start_date.setDisplayFormat("yyyy-MM-dd") self.table.setCellWidget(row, 1, start_date)
end_date = QDateEdit() end_date.setDate(today.addDays(1)) end_date.setCalendarPopup(True) end_date.setDisplayFormat("yyyy-MM-dd") self.table.setCellWidget(row, 2, end_date)
def delete_row(self): """删除选中行""" current_row = self.table.currentRow() if current_row >= 0: self.table.removeRow(current_row)
def get_data(self): """从表格获取数据""" data = [] for row in range(self.table.rowCount()): name_item = self.table.item(row, 0) start_widget = self.table.cellWidget(row, 1) end_widget = self.table.cellWidget(row, 2)
if ( name_item is not None and start_widget is not None and end_widget is not None ): try: name = name_item.text().strip()
start_qdate = start_widget.date() end_qdate = end_widget.date()
start_date = datetime( start_qdate.year(), start_qdate.month(), start_qdate.day() ) end_date = datetime( end_qdate.year(), end_qdate.month(), end_qdate.day() )
display_name = name.strip() data.append( { "name": name, "display_name": display_name, "start": start_date, "end": end_date, } ) except Exception as e: QMessageBox.warning( self, "数据格式错误", f"第{row+1}行数据错误: {e}" ) return None return data
def generate_image(self): """生成时间表图片""" data = self.get_data() if not data: QMessageBox.warning(self, "数据错误", "没有有效数据") return
for i, item in enumerate(data): if item["end"] <= item["start"]: QMessageBox.warning(self, "日期错误", f"第{i+1}行:结束日期必须大于开始日期") return
title = self.title_input.text().strip() if not title: title = "时间表"
file_path, _ = QFileDialog.getSaveFileName( self, "保存图片", f"{title}.png", "PNG Images (*.png)" )
if file_path: try: self.create_timeline_image(title, data, file_path) QMessageBox.information(self, "成功", f"图片已保存到: {file_path}") except Exception as e: QMessageBox.critical(self, "生成失败", f"生成图片时出错: {e}")
def create_timeline_image(self, title, data, output_path): """创建时间表图片""" width = 1400 height = 200 + len(data) * 70
image = Image.new("RGB", (width, height), "white") draw = ImageDraw.Draw(image)
try: title_font = ImageFont.truetype("simhei.ttf", 32) item_font = ImageFont.truetype("simhei.ttf", 20) date_font = ImageFont.truetype("simhei.ttf", 14) small_font = ImageFont.truetype("simhei.ttf", 12) except: title_font = ImageFont.load_default() item_font = ImageFont.load_default() date_font = ImageFont.load_default() small_font = ImageFont.load_default()
title_bbox = draw.textbbox((0, 0), title, font=title_font) title_width = title_bbox[2] - title_bbox[0] title_x = (width - title_width) // 2 draw.text((title_x, 30), title, fill="black", font=title_font)
all_starts = [item["start"] for item in data] all_ends = [item["end"] for item in data] min_date = min(all_starts) max_date = max(all_ends) date_range = max(1, (max_date - min_date).days)
chart_top = 100 chart_bottom = height - 50 chart_left = 250 chart_right = width - 50 chart_width = chart_right - chart_left row_height = 60
timeline_y = chart_bottom - 20 draw.line( [(chart_left, timeline_y), (chart_right, timeline_y)], fill="black", width=2 )
start_year = min_date.year end_year = max_date.year
for year in range(start_year, end_year + 2): year_date = datetime(year, 1, 1) if year_date < min_date: continue
days_from_start = (year_date - min_date).days x_pos = chart_left + (days_from_start / date_range) * chart_width
if chart_left <= x_pos <= chart_right: draw.line( [(x_pos, chart_top), (x_pos, timeline_y)], fill="lightgray", width=1 ) year_str = f"{year}" year_bbox = draw.textbbox((0, 0), year_str, font=small_font) year_width = year_bbox[2] - year_bbox[0] draw.text( (x_pos - year_width // 2, timeline_y + 10), year_str, fill="gray", font=small_font, )
colors = [ "#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4", "#FFEAA7", "#DDA0DD", "#98D8C8", "#F7DC6F", ]
for i, item in enumerate(data): row_y = chart_top + i * row_height
start_days = (item["start"] - min_date).days end_days = (item["end"] - min_date).days
original_start_x = chart_left + (start_days / date_range) * chart_width original_end_x = chart_left + (end_days / date_range) * chart_width
start_x = original_start_x end_x = original_end_x
min_bar_width = 15 if end_x - start_x < min_bar_width: center_x = (original_start_x + original_end_x) / 2 start_x = max(chart_left, center_x - min_bar_width / 2) end_x = min(chart_right, center_x + min_bar_width / 2)
bar_height = 25 bar_y = row_y - bar_height // 2
color = colors[i % len(colors)] draw.rounded_rectangle( [start_x, bar_y, end_x, bar_y + bar_height], radius=3, fill=color, outline="darkgray", width=1, )
display_name = item["display_name"] name_bbox = draw.textbbox((0, 0), display_name, font=item_font) draw.text( (50, row_y - name_bbox[3] // 2), display_name, fill="black", font=item_font, )
start_str = item["start"].strftime("%Y-%m-%d") end_str = item["end"].strftime("%Y-%m-%d")
start_bbox = draw.textbbox((0, 0), start_str, font=date_font) end_bbox = draw.textbbox((0, 0), end_str, font=date_font) start_text_width = start_bbox[2] - start_bbox[0] end_text_width = end_bbox[2] - end_bbox[0]
date_spacing = ( (original_end_x - original_start_x) / chart_width * date_range )
if date_spacing < 30: mid_x = (start_x + end_x) / 2 date_str = f"{start_str} ~ {end_str}" date_bbox = draw.textbbox((0, 0), date_str, font=date_font) date_width = date_bbox[2] - date_bbox[0]
date_x = mid_x - date_width / 2 date_x = max(chart_left + 5, min(date_x, chart_right - date_width - 5))
draw.text( (date_x, bar_y + bar_height + 5), date_str, fill="darkblue", font=date_font, )
draw.line( [ (original_start_x, bar_y + bar_height), (original_start_x, bar_y + bar_height + 15), ], fill="gray", width=1, ) draw.line( [ (original_end_x, bar_y + bar_height), (original_end_x, bar_y + bar_height + 15), ], fill="gray", width=1, ) else: label_start_x = original_start_x label_end_x = original_end_x
start_text_x = label_start_x - start_text_width / 2
if start_text_x < chart_left + 5: start_text_x = chart_left + 5 elif ( start_text_x + start_text_width > label_end_x - end_text_width - 10 ): start_text_x = max(chart_left + 5, label_start_x - start_text_width)
draw.text( (start_text_x, bar_y + bar_height + 5), start_str, fill="darkgreen", font=date_font, )
end_text_x = label_end_x - end_text_width / 2
if end_text_x + end_text_width > chart_right - 5: end_text_x = chart_right - end_text_width - 5 elif end_text_x < start_text_x + start_text_width + 10: end_text_x = min(chart_right - end_text_width - 5, label_end_x)
draw.text( (end_text_x, bar_y + bar_height + 5), end_str, fill="darkred", font=date_font, )
draw.line( [ (original_start_x, bar_y + bar_height), (original_start_x, bar_y + bar_height + 5), ], fill="gray", width=1, ) draw.line( [ (original_end_x, bar_y + bar_height), (original_end_x, bar_y + bar_height + 5), ], fill="gray", width=1, )
image.save(output_path)
def main(): app = QApplication(sys.argv) window = TimelineGenerator() window.show() sys.exit(app.exec())
if __name__ == "__main__": main()
|