wxPython 甘特图制作教程:简单示例代码
要在 wxPython 中创建甘特图,可以使用 wxPython 的绘图功能和事件处理函数来实现。
以下是一个简单的示例代码,用于创建一个基本的甘特图:
import wx
import wx.lib.agw.flatnotebook as fnb
import random
class GanttChart(wx.Panel):
def __init__(self, parent):
super().__init__(parent)
self.tasks = [
{'name': 'Task 1', 'start': 0, 'end': 5},
{'name': 'Task 2', 'start': 3, 'end': 8},
{'name': 'Task 3', 'start': 6, 'end': 10},
# 添加更多任务...
]
self.Bind(wx.EVT_PAINT, self.OnPaint)
def OnPaint(self, event):
dc = wx.PaintDC(self)
dc.Clear()
chart_width = self.GetClientSize().GetWidth()
chart_height = self.GetClientSize().GetHeight()
# 绘制甘特图的背景
dc.SetBrush(wx.Brush(wx.Colour(240, 240, 240)))
dc.DrawRectangle(0, 0, chart_width, chart_height)
# 绘制任务条
bar_height = chart_height / len(self.tasks)
for i, task in enumerate(self.tasks):
bar_x = task['start'] * chart_width
bar_width = (task['end'] - task['start']) * chart_width
dc.SetBrush(wx.Brush(wx.Colour(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))))
dc.DrawRectangle(bar_x, i * bar_height, bar_width, bar_height)
dc.SetTextForeground(wx.BLACK)
dc.DrawText(task['name'], bar_x + 5, i * bar_height + 5)
class MainFrame(wx.Frame):
def __init__(self):
super().__init__(None, title='Gantt Chart', size=(800, 600))
notebook = fnb.FlatNotebook(self)
gantt_panel = GanttChart(notebook)
notebook.AddPage(gantt_panel, 'Gantt Chart')
self.Show()
app = wx.App()
frame = MainFrame()
app.MainLoop()
在这个例子中,我们创建了一个继承自 wx.Panel 的 GanttChart 类,用于绘制甘特图。在 GanttChart 的构造函数中,我们定义了一个任务列表,每个任务包含名称、开始时间和结束时间。然后,我们绑定了 EVT_PAINT 事件处理函数 OnPaint,在该函数中绘制甘特图的背景和任务条。
在 MainFrame 类中,我们创建了一个 FlatNotebook 控件,并在其中添加了一个 GanttChart 面板。
最后,我们创建了一个 wx.App 实例并启动主事件循环。
运行这个示例代码,将会打开一个包含一个甘特图的窗口。您可以根据需要修改任务列表和绘制甘特图的方式来满足自己的需求。
原文地址: https://www.cveoy.top/t/topic/o4LK 著作权归作者所有。请勿转载和采集!