""" Um relógio com GTK. """ import datetime # GTK e outros módulos associados import gtk import gtk.glade import gobject import pango class Relogio(object): """ Implementa a janela principal do programa. """ def __init__(self): """ Inicializa a classe. """ # Carrega a interface self.tree = gtk.glade.XML('relogio.glade', 'main') # Liga os eventos callbacks = { 'on_main_destroy': self.on_main_destroy, 'on_imagemenuitem5_activate': self.on_main_destroy, 'on_imagemenuitem10_activate': self.on_imagemenuitem10_activate } self.tree.signal_autoconnect(callbacks) # Coloca um título na janela self.tree.get_widget('main').set_title('Relógio') # O rótulo que reberá a hora self.hora = self.tree.get_widget('lbl_hora') # A barra de status que reberá a data self.data = self.tree.get_widget('sts_data') print dir(self.data) # Muda a fonte do rótulo self.hora.modify_font(pango.FontDescription('verdana 28')) # Um temporizador para manter a hora atualizada self.timer = gobject.timeout_add(1000, self.on_timer) def on_imagemenuitem10_activate(self, widget): """ Cria a janela de "Sobre". """ # Caixa de dialogo dialog = gtk.MessageDialog(parent=self.tree.get_widget('main'), flags=gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, type=gtk.MESSAGE_OTHER, buttons=gtk.BUTTONS_OK, message_format='Primeiro exemplo usando GTK.') dialog.set_title('Sobre') dialog.set_position(gtk.WIN_POS_CENTER_ALWAYS) # Exibe a caixa dialog.run() dialog.destroy() return def on_timer(self): """ Rotina para o temporizador. """ # Pega a hora do sistema hora = datetime.datetime.now().time().isoformat().split('.')[0] # Muda o texto do rótulo self.hora.set_text(hora) # Pega a data do sistema em formato ISO data = datetime.datetime.now().date().isoformat() data = 'Data: ' + '/'.join(data.split('-')[::-1]) # Coloca a data na barra de status self.data.push(0, data) # Verdadeiro faz com que o temporizador rode de novo return True def on_main_destroy(self, widget): """ Termina o programa. """ raise SystemExit if __name__ == "__main__": # Inicia a GUI relogio = Relogio() gtk.main() True False GTK_WIN_POS_CENTER True True True _Arquivo True True True gtk-quit True True True Aj_uda True True True gtk-about True True False 300 150 True 5 5 1 True 2 False 2 """ Rodando programas com GTK. """ import subprocess import gtk import gtk.glade import gobject import pango class Exec(object): """ Janela principal. """ def __init__(self): """ Inicializa a classe. """ # Carrega a interface self.tree = gtk.glade.XML('cmd.glade', 'main') # Liga os eventos callbacks = { 'on_main_destroy': self.on_main_destroy, 'on_btn_fechar_clicked': self.on_main_destroy, 'on_btn_rodar_clicked': self.on_btn_rodar_clicked } self.tree.signal_autoconnect(callbacks) def on_btn_rodar_clicked(self, widget): """ Roda o comando. """ ntr_cmd = self.tree.get_widget('ntr_cmd') chk_shell = self.tree.get_widget('chk_shell') cmd = ntr_cmd.get_text() if cmd: # chk_shell.state será 1 se chk_shell estiver marcado if chk_shell.state: cmd = 'cmd start cmd /c ' + cmd subprocess.Popen(args=cmd) else: # Caixa de dialogo dialog = gtk.MessageDialog(parent=self.tree.get_widget('main'), flags=gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, type=gtk.MESSAGE_OTHER, buttons=gtk.BUTTONS_OK, message_format='Digite um comando.') dialog.set_title('Mensagem') dialog.set_position(gtk.WIN_POS_CENTER_ALWAYS) # Exibe a caixa dialog.run() dialog.destroy() return True def on_main_destroy(self, widget): """ Termina o programa. """ raise SystemExit if __name__ == "__main__": # Inicia a GUI exe = Exec() gtk.main() 380 100 True Entre com um comando... False True GTK_WIN_POS_CENTER 380 100 True 100 29 True True True _Rodar True 0 167 61 100 29 True True True _Fechar True 0 272 61 365 29 True True 9 14 136 29 True True _Janela de texto True 0 True 11 59 # importa wxPython import wx class Main(wx.Frame): """ Classe que define a janela principal do programa. """ def __init__(self, parent, id, title): """ Inicializa a classe. """ # Define a janela usando o __init__ da classe mãe wx.Frame.__init__(self, parent, id, title, size=(600, 400)) # Cria uma caixa de texto self.text = wx.TextCtrl(self, style=wx.TE_MULTILINE) # Pega o fonte do programa (decodificado para latin1) font = file(__file__, 'rb').read().decode('latin1') # Carrega o fonte do programa na caixa de texto self.text.SetLabel(font) # Mostra a janela self.Show(True) if __name__ == '__main__': # Cria um objeto "aplicação" do wxPython app = wx.App() # Cria um objeto "janela" a partir da classe frame = Main(None, wx.ID_ANY, 'Fonte') # Inicia o loop de tratamento de eventos app.MainLoop() import wx import time class Main(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(150, 80)) clock = time.asctime().split()[3] # Cria um rótulo de texto self.control = wx.StaticText(self, label=clock) # Muda a fonte self.control.SetFont(wx.Font(22, wx.SWISS, wx.NORMAL, wx.BOLD)) # Cria um timer TIMER_ID = 100 self.timer = wx.Timer(self, TIMER_ID) # Inicia o timer self.timer.Start(1000) # Associa os métodos com os eventos wx.EVT_TIMER(self, TIMER_ID, self.on_timer) wx.EVT_CLOSE(self, self.on_close) self.Show(True) def on_timer(self, event): # Atualiza o relógio clock = time.asctime().split()[3] self.control.SetLabel(clock) def on_close(self, event): # Para o timer self.timer.Stop() self.Destroy() app = wx.App() Main(None, wx.ID_ANY, 'Relógio') app.MainLoop() import wx # Identificadores para as opções do menu ID_FILE_OPEN = wx.NewId() ID_FILE_SAVE = wx.NewId() ID_FILE_EXIT = wx.NewId() ID_HELP_ABOUT = wx.NewId() class Main(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title) # Cria o menu arquivo filemenu = wx.Menu() # Cria as opções filemenu.Append(ID_FILE_OPEN, 'Abrir arquivo...') filemenu.Append(ID_FILE_SAVE, 'Salvar') filemenu.AppendSeparator() filemenu.Append(ID_FILE_EXIT, 'Sair') # Cria o menu ajuda helpmenu = wx.Menu() helpmenu.Append(ID_HELP_ABOUT, 'Sobre...') # Cria o menu menubar = wx.MenuBar() menubar.Append(filemenu, 'Arquivo') menubar.Append(helpmenu, 'Ajuda') self.SetMenuBar(menubar) # Associa métodos aos eventos de menu wx.EVT_MENU(self, ID_FILE_OPEN, self.on_open) wx.EVT_MENU(self, ID_FILE_SAVE, self.on_save) wx.EVT_MENU(self, ID_FILE_EXIT, self.on_exit) wx.EVT_MENU(self, ID_HELP_ABOUT, self.about) # Cria uma caixa de texto self.control = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE) self.fn = '' def on_open(self, evt): # Abre uma caixa de dialogo escolher arquivo dialog = wx.FileDialog(None, style=wx.OPEN) d = dialog.ShowModal() if d == wx.ID_OK: # Pega o arquivo escolhido self.fn = dialog.GetPath() # Muda o título da janela self.SetTitle(self.fn) # Carrega o texto na caixa de texto self.control.SetLabel(file(self.fn, 'rb').read()) dialog.Destroy() def on_save(self, evt): # Salva o texto na caixa de texto if self.fn: file(self.fn, 'wb').write(self.control.GetLabel()) def on_exit(self, evt): # Fecha a janela principal self.Close(True) def about(self, evt): dlg = wx.MessageDialog(self, 'Exemplo wxPython', 'Sobre...', wx.OK | wx.ICON_INFORMATION) dlg.ShowModal() dlg.Destroy() app = wx.App() frame = Main(None , wx.ID_ANY, 'Isto é quase um editor...') frame.Show(True) app.MainLoop() import wx class Main(wx.Frame): def __init__(self, parent, id, title): # Cria janela wx.Frame.__init__(self, parent, id, title, size=(300, 150)) self.Centre() self.Show(True) # Cria um texto estático self.text = wx.StaticText(self, label='Entre com uma expressão:', pos=(10, 10)) # Cria uma caixa de edição de texto self.edit = wx.TextCtrl(self, size=(250, -1), pos=(10, 30)) # Cria um botão self.button = wx.Button(self, label='ok', pos=(10, 60)) # Conecta um método ao botão self.button.Bind(wx.EVT_BUTTON, self.on_button) def on_button(self, event): # Pega o valor da caixa de texto txt = self.edit.GetValue() # Tenta resolver e apresentar a expressão try: wx.MessageBox(txt + ' = ' + str(eval(txt)), 'Resultado') # Se algo inesperado ocorrer except: wx.MessageBox('Expressão inválida', 'Erro') app = wx.App() Main(None, -1, 'Teste de MessageBox') app.MainLoop() import sys from PyQt4 import QtGui, QtCore class Main(QtGui.QWidget): """ Janela principal """ def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) # Muda a geometria da janela self.setGeometry(200, 200, 200, 100) # Muda o título self.setWindowTitle('Teste') # Cria um botão quit = QtGui.QPushButton('Fechar', self) quit.setGeometry(10, 10, 60, 35) # Conecta o sinal gerado pelo botão com a função # que encerra o programa self.connect(quit, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()')) # Cria um objeto "aplicação Qt", que trata os eventos app = QtGui.QApplication(sys.argv) # Cria a janela principal qb = Main() qb.show() # Inicia a "aplicação Qt" sys.exit(app.exec_()) Dialog 0 0 116 108 Dialog 20 20 75 23 Mensagem 20 60 75 23 Fechar fim clicked() Dialog close() 57 71 57 53 import sys import time from PyQt4 import QtCore, QtGui # Módulo gerado pelo pyuic from dialog import Ui_Dialog class Main(QtGui.QMainWindow): """ Janela principal """ def __init__(self, parent=None): """ Inicialização da janela """ QtGui.QWidget.__init__(self, parent) # Cria um objeto a partir da interface gerada pelo pyuic self.ui = Ui_Dialog() self.ui.setupUi(self) # Conecta o método ao botão que foi definido através do Qt Designer self.connect(self.ui.msg, QtCore.SIGNAL('clicked()'), self.show_msg) def show_msg(self): """ Método que evoca a caixa de mensagem """ reply = QtGui.QMessageBox.question(self, 'Messagem', 'Hora: ' + time.asctime().split()[3], QtGui.QMessageBox.Ok) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) myapp = Main() myapp.show() sys.exit(app.exec_())