首頁‎ > ‎Python程式語言‎ > ‎

簡易播放清單與資料庫


資料庫檔案,下載後放置於playlistsdb.py相同目錄中。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
#author http://www.pastwind.org/ Ryan Ho
#license http://opensource.org/licenses/gpl-2.0.php GNU Public License ver. 2.0
 
#playlistsdb.py
 
import wx, sys
import sqlite3
 
class PlaylistsDB(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title)
 
#開啟資料庫檔案,並建立連接
self.plsdb = './plsdb.sqlite3'
self.plsdb_conn = sqlite3.connect(str(self.plsdb))
self.c_plsdb = self.plsdb_conn.cursor()
 
vbox = wx.BoxSizer(wx.VERTICAL)
 
# wx.ListCtrl範例,放置playlists用
hbox1 = wx.BoxSizer(wx.HORIZONTAL)
tracklist = wx.ListCtrl(self, -1, style=wx.LC_REPORT)
tracklist.InsertColumn(0, 'Playing')
tracklist.InsertColumn(1, 'Track No')
tracklist.InsertColumn(2, 'Title / Track Artist')
tracklist.InsertColumn(3, 'Duration')
hbox1.Add(tracklist, 1, wx.EXPAND)
vbox.Add(hbox1, 1, wx.EXPAND)
 
# 幾個按鈕,沒有大作用
hbox2 = wx.BoxSizer(wx.HORIZONTAL)
panel = wx.Panel(self, -1)
db_init_bt = wx.Button(panel, 0, '資料庫初始化')
db_add = wx.Button(panel, 1, '增加資料')
db_del = wx.Button(panel, -1, '刪除資料')
hbox2.Add(db_init_bt, 0, wx.ALL, 10)
hbox2.Add(db_add, 0, wx.ALL, 10)
hbox2.Add(db_del, 0, wx.ALL, 10)
panel.SetSizer(hbox2)
vbox.Add(panel, 0, wx.EXPAND)
 
# 隱藏放了上述幾個按鈕的panel,要打開來看就加註解
panel.Hide()
 
self.SetSizer(vbox)
 
self.Centre()
self.Show(True)
 
# 關閉與按鈕事件定義
self.Bind(wx.EVT_CLOSE, self.OnClose)
self.Bind(wx.EVT_BUTTON, self.OnDBinit, id=0)
self.Bind(wx.EVT_BUTTON, self.OnAddtrack, id=1)
 
# 從資料庫撈資料,然後丟到ListCtrl
self.c_plsdb.execute('select * from tracklists')
for i in self.c_plsdb:
index = tracklist.InsertStringItem(sys.maxint, '')
# 從sqlite3抓的資料要作型態轉換(轉字串),才能丟給wxWidgets吃,搞了好久才發覺 Orz
tracklist.SetStringItem(index, 1, str(i[0]))
ta = i[1] + ' / ' + i[2]
tracklist.SetStringItem(index, 2, unicode(ta))
tracklist.SetStringItem(index, 3, str(i[3]))
 
# 關閉事件的動作
def OnClose(self, event):
self.c_plsdb.close()
self.Destroy()
 
# 資料庫初始化
def OnDBinit(self, event):
self.c_plsdb.execute('''create table tracklists(trackno integer, title text, artist text, duration text)''')
 
# 增加資料到資料庫中
def OnAddtrack(self, event):
for i in albums:
self.c_plsdb.execute('insert into tracklists values (?,?,?,?)', i)
self.plsdb_conn.commit()
 
 
if __name__ == '__main__':
app = wx.App()
wx.InitAllImageHandlers()
PlaylistsDB(None, -1, 'Playlists')
app.MainLoop()
Comments