在这篇Python GUI文章中,我们将向您展示在wxPython中创建PrintDialog打印对话框。使用PrintDialog您将有一个很好的对话框来打印文档。
下面是使用Python的GUI库wxPython创建字体对话框的完整代码。
import wx
class MyFrame(wx.Frame):
def __init__(self, parent, title):
super(MyFrame, self).__init__(parent, title =title, size = (800,600))
self.panel = MyPanel(self)
class MyPanel(wx.Panel):
def __init__(self, parent):
super(MyPanel, self).__init__(parent)
self.button = wx.Button(self, label = "www.linuxmi.com - 打印对话框", pos = (100,100))
self.Bind(wx.EVT_BUTTON, self.openDialog)
def openDialog(self, event):
data = wx.PrintDialogData()
data.EnableSelection(True)
data.EnablePrintToFile(True)
data.EnablePageNumbers(True)
data.SetMinPage(1)
data.SetMaxPage(10)
dialog = wx.PrintDialog(self, data)
#dialog.ShowModal()
if dialog.ShowModal() == wx.ID_OK:
data = dialog.GetPrintDialogData()
print('GetAllPages: %d\n' % data.GetAllPages())
dialog.Destroy()
class MyApp(wx.App):
def OnInit(self):
self.frame = MyFrame(parent=None, title="打印对话框")
self.frame.Show()
return True
app = MyApp()
app.MainLoop()
首先,我们创建了MyFrame。这个类是一个从wx继承的顶级窗口框架,我们在这里创建了MyPanel类的对象
class MyFrame(wx.Frame):
def __init__(self, parent, title):
super(MyFrame, self).__init__(parent, title =title, size = (800,600))
self.panel = MyPanel(self)
这是我们的MyPanel类,它继承了wx.Panel,我们在这个类中创建了一个按钮,并且在这个类中创建了事件绑定过程。
class MyPanel(wx.Panel):
def __init__(self, parent):
super(MyPanel, self).__init__(parent)
self.button = wx.Button(self, label = "www.linuxmi.com - 打印对话框", pos = (100,100))
self.Bind(wx.EVT_BUTTON, self.openDialog)
这个方法是用来创建PrintDialog的,在顶部你可以看到我们已经把这个方法和按钮绑定在一起了。因此,当用户单击该按钮时,将打开一个PrintDialog。
def openDialog(self, event):
data = wx.PrintDialogData()
data.EnableSelection(True)
data.EnablePrintToFile(True)
data.EnablePageNumbers(True)
data.SetMinPage(1)
data.SetMaxPage(10)
dialog = wx.PrintDialog(self, data)
#dialog.ShowModal()
if dialog.ShowModal() == wx.ID_OK:
data = dialog.GetPrintDialogData()
print('GetAllPages: %d\n' % data.GetAllPages())
dialog.Destroy()
最后一个类是MyApp类继承自wx.App。OnInit()方法通常是创建框架子类对象(frame subclass objects)。
然后开始我们的主循环(main loop)。就是这样。一旦应用程序的主事件循环处理接管,控制权就传递给wxPython。与过程性程序不同,wxPython GUI程序主要响应在其周围发生的事件,这些事件主要由用户用鼠标单击和键盘输入决定。当应用程序中的所有帧都被关闭时,app.MainLoop()方法将返回,程序将退出。
class MyApp(wx.App):
def OnInit(self):
self.frame = MyFrame(parent=None, title="打印对话框")
self.frame.Show()
return True
app = MyApp()
app.MainLoop()
运行完整代码,结果如下: