wxpython制作数据库登录
时间: 2023-11-10 20:05:52 浏览: 123
下面是一个简单的 wxPython 实现的数据库登录窗口示例:
```python
import wx
import pymysql
class LoginFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'Database Login', size=(300, 200))
panel = wx.Panel(self, -1)
vbox = wx.BoxSizer(wx.VERTICAL)
hbox1 = wx.BoxSizer(wx.HORIZONTAL)
self.host_label = wx.StaticText(panel, -1, 'Host:', size=(50, -1))
hbox1.Add(self.host_label, flag=wx.RIGHT, border=10)
self.host_text = wx.TextCtrl(panel, -1, 'localhost')
hbox1.Add(self.host_text, proportion=1)
vbox.Add(hbox1, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
hbox2 = wx.BoxSizer(wx.HORIZONTAL)
self.user_label = wx.StaticText(panel, -1, 'User:', size=(50, -1))
hbox2.Add(self.user_label, flag=wx.RIGHT, border=10)
self.user_text = wx.TextCtrl(panel, -1, '')
hbox2.Add(self.user_text, proportion=1)
vbox.Add(hbox2, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
hbox3 = wx.BoxSizer(wx.HORIZONTAL)
self.password_label = wx.StaticText(panel, -1, 'Password:', size=(50, -1))
hbox3.Add(self.password_label, flag=wx.RIGHT, border=10)
self.password_text = wx.TextCtrl(panel, -1, '', style=wx.TE_PASSWORD)
hbox3.Add(self.password_text, proportion=1)
vbox.Add(hbox3, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
hbox4 = wx.BoxSizer(wx.HORIZONTAL)
self.database_label = wx.StaticText(panel, -1, 'Database:', size=(50, -1))
hbox4.Add(self.database_label, flag=wx.RIGHT, border=10)
self.database_text = wx.TextCtrl(panel, -1, '')
hbox4.Add(self.database_text, proportion=1)
vbox.Add(hbox4, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
hbox5 = wx.BoxSizer(wx.HORIZONTAL)
self.connect_button = wx.Button(panel, -1, 'Connect')
hbox5.Add(self.connect_button, flag=wx.RIGHT, border=10)
self.cancel_button = wx.Button(panel, -1, 'Cancel')
hbox5.Add(self.cancel_button)
vbox.Add(hbox5, flag=wx.ALIGN_RIGHT|wx.RIGHT|wx.BOTTOM, border=10)
panel.SetSizer(vbox)
self.connect_button.Bind(wx.EVT_BUTTON, self.on_connect)
self.cancel_button.Bind(wx.EVT_BUTTON, self.on_cancel)
def on_connect(self, event):
host = self.host_text.GetValue()
user = self.user_text.GetValue()
password = self.password_text.GetValue()
database = self.database_text.GetValue()
try:
conn = pymysql.connect(host=host, user=user, password=password, database=database)
print('Connected to database.')
conn.close()
except pymysql.Error as e:
print('Error connecting to database:', e)
def on_cancel(self, event):
self.Close()
if __name__ == '__main__':
app = wx.App()
frame = LoginFrame()
frame.Show()
app.MainLoop()
```
在这个示例中,我们使用 wxPython 的各种布局管理器来创建一个简单的登录窗口,包括四个文本框和两个按钮,其中 Connect 按钮用于连接数据库,Cancel 按钮用于关闭窗口。
当用户单击 Connect 按钮时,我们通过 pymysql 模块连接到数据库。如果连接成功,则在控制台输出 "Connected to database.",否则输出错误消息。
注意,这个示例中的数据库连接是非常简单的,只是用于演示 wxPython 中如何创建登录窗口和连接到数据库。在实际应用中,需要根据实际需求进行更复杂的错误处理和安全措施。
阅读全文