QMessage is working fine in a class function but not in separate function - pyqt5

Here is my code :
def er():
print("connection error")
from PyQt5.QtWidgets import QMessageBox
msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
msg.setText("Some text ")
msg.setInformativeText("info text")
msg.setWindowTitle("title")
msg.setStandardButtons(QMessageBox.Ok)
retval = msg.exec_()
print(retval)
if __name__ == '__main__':
mac = (':'.join(['{:02x}'.format((getnode() >> i) & 0xff) for i in range(0,8 * 6, 8)][::-1]))
if mac == 'b8:e8:56:24:96:30':
print("OK")
some_function
else:
er()
and the error is 'QWidget: Must construct a QApplication before a QWidget'

You have to init the qt event loop with QApplication first, like the error message said
def er():
print("connection error")
from PyQt5.QtWidgets import QMessageBox,QApplication
import sys
app = QApplication(sys.argv)
msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
msg.setText("Some text ")
msg.setInformativeText("info text")
msg.setWindowTitle("title")
msg.setStandardButtons(QMessageBox.Ok)
retval = msg.exec_()
print(retval)
if __name__ == '__main__':
mac = (':'.join(['{:02x}'.format((getnode() >> i) & 0xff) for i in range(0, 8 * 6, 8)][::-1]))
if mac == 'b8:e8:56:24:96:30':
print("OK")
some_function
else:
er()

Related

QMediaPlayer.setVideoOutput frozen

I tried to add videowidget to QFrame inside QstackedWidget but when i use QMediaPlayer.setVideoOutput the program run but
frozen, when i click on the window it just give beeping sound. when i comment the setVideoOutput it
run just fine.
`class halaman_belajar(QWidget):
def init(self):
super().init()
uic.loadUi(".\Asset\GuiHalamanBelajar.ui", self)
self.kembali_menu.clicked.connect(self.kembali)
self.kembali_menu.setCursor(QCursor(Qt.PointingHandCursor))
self.kembali_menu.setShortcut("esc")
self.bab_selanjutnya.clicked.connect(self.selanjutnya)
self.bab_selanjutnya.setCursor(QCursor(Qt.PointingHandCursor))
self.bab_selanjutnya.setShortcut(Qt.Key_Right)
self.bab_sebelumnya.clicked.connect(self.sebelumnya)
self.bab_sebelumnya.setCursor(QCursor(Qt.PointingHandCursor))
self.bab_sebelumnya.setShortcut(Qt.Key_Left)
self.halaman_isi.setCurrentIndex(0)
self.bab_sebelumnya.setEnabled(False)
if self.halaman_isi.currentIndex == 0:
self.bab_sebelumnya.setEnabled(False)
else:
self.bab_sebelumnya.setEnabled(True)
#Combo Box
self.pintasan_halaman.activated.connect(self.pintasanhalaman)
#video player
video = QVideoWidget()
self.videoproklamasi = QMediaPlayer(None, QMediaPlayer.VideoSurface)
self.videoproklamasi.setMedia(QMediaContent(QUrl.fromLocalFile("E:\ProjectHistoryApp\Asset\proklamasi.mp4")))
#self.videoproklamasi.setVideoOutput(video)
self.play = QPushButton()
self.play.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
#self.play.clicked.connect(self.mulaivideo)
self.slider= QSlider(Qt.Horizontal)
self.slider.setRange(0,0)
self.wadahnisor = QHBoxLayout()
self.wadahnisor.setContentsMargins(0,0,0,0)
self.wadahnisor.addWidget(self.play)
self.wadahnisor.addWidget(self.slider)
self.wadahvideo = QVBoxLayout(self.isi_video)
self.wadahvideo.addWidget(video)
self.wadahvideo.addLayout(self.wadahnisor)
def kembali(self):
pesan2 = QMessageBox()
pesan2.setWindowTitle("Status")
pesan2.setText("Kembali Ke Menu?")
pesan2.setWindowIcon(QIcon(".\Asset\Mascot.png"))
pesan2.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
hasil = pesan2.exec()
if hasil == QMessageBox.Yes:
show_halaman.setCurrentIndex(show_halaman.currentIndex() - 1)
def selanjutnya(self):
self.halaman_isi.setCurrentIndex(self.halaman_isi.currentIndex() + 1)
self.bab_sebelumnya.setEnabled(True)
#if halaman_isi.currentIndex == 10:
#self.bab_selanjutnya.setEnabled(False)
def sebelumnya(self):
self.halaman_isi.setCurrentIndex(self.halaman_isi.currentIndex() - 1)
if self.halaman_isi.currentIndex() == 0:
self.bab_sebelumnya.setEnabled(False)
def pintasanhalaman(self):
self.halaman_isi.setCurrentIndex(self.pintasan_halaman.currentIndex())
if self.halaman_isi.currentIndex() != 0:
self.bab_sebelumnya.setEnabled(True)
def mulaivideo(self):
if self.videoproklamasi.state() == QMediaPlayer.PlayingState():
self.videoproklamasi.pause()
else:
self.videoproklamasi.play()`

PYQT5 imported MDI Subwindow Scaled Up

I'm working on a gui tool-- I'm building it with Pyqt5. I'm speifically NOT using QT designer. I'm using an MDI widget to keep everyhing a bit tidier.
Furthermore, so that my code is more crisp and less redundant, I'm building out each child window in a separate window in the same directory and then just importing the appropriate class from the individual files.
The problem is, whenver I import the subwindows, the are scaled up in the MDI subwindow. I am at a loss as to how I can address this. Has anyone expierenced something similar? I've added simplied code for my MDI subwindow below, followed by the code for one of the subwindows thta I'm importing. Any assistance would be greatly appreciated.
Import sys
from PyQt5 import QtCore
from PyQt5.QtGui import *
from PyQt5.QtGui import QWindow
from PyQt5.QtWidgets import *
from PyQt5.QtWidgets import QMdiArea, QAction, QMdiSubWindow, QTextEdit
from Admission_Tool import *
from COPD_tool import *
from Discharge_Template import DischargeWindow
from Note_Template import *
class MDIWindow(QMainWindow):
count = 0
htntoolcount = 0
copdcount = 0
def __init__(self):
super().__init__()
self.mdi = QMdiArea()
self.setCentralWidget(self.mdi)
self.setStyleSheet('font-size: 10pt; font-family: Times;')
self.setStyleSheet("QPushButton{font-size: 10pt;}")
self.setStyleSheet("QLabel{font-size: 10pt;}")
self.mdi.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
self.mdi.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
#####Setting up main Menu Labels and Buttons#####
self.mainMenuWidget = QWidget(self)
self.mmWidgetLayout = QVBoxLayout()
self.mainMenuWidget.setLayout(self.mmWidgetLayout)
self.mainMenuWidget.setWindowTitle("Main Menu")
self.mmButton1 = QPushButton("Note Setup Tool", self)
self.mmButton2 = QPushButton("Lab Entry Tool", self)
self.mmButton3 = QPushButton("Follow Up Tools", self)
self.mmButton4 = QPushButton("ROS Generator", self)
self.mmButton5 = QPushButton("Physical Exam Generator", self)
self.mmButton6 = QPushButton("Cardon Matrix", self)
self.mmButton7 = QPushButton("Trilogy Matrix", self)
self.mmButton8 = QPushButton("ASC Matrix", self)
self.mmButton9 = QPushButton("Proactive Email", self)
self.mmWidgetLayout.addWidget(self.mmButton1)
self.mmWidgetLayout.addWidget(self.mmButton2)
self.mmWidgetLayout.addWidget(self.mmButton3)
self.mmWidgetLayout.addWidget(self.mmButton4)
self.mmWidgetLayout.addWidget(self.mmButton5)
self.mmWidgetLayout.addWidget(self.mmButton6)
self.mmWidgetLayout.addWidget(self.mmButton7)
self.mmWidgetLayout.addWidget(self.mmButton8)
self.mmWidgetLayout.addWidget(self.mmButton9)
self.mdi.addSubWindow(self.mainMenuWidget)
self.mainMenuWidget.show()
##adding actions to main menu buttons##
self.mmButton1.clicked.connect(self.noteSetupFunc)
self.mmButton2.clicked.connect(self.admissionTool)
self.mmButton3.clicked.connect(self.COPDToolFunc)
self.setWindowTitle("Proactive Charting Tool")
def noteSetupFunc(self):
self.noteSUButtFuncWidget = NOTEWindow()
self.mdi.addSubWindow(self.noteSUButtFuncWidget)
self.noteSUButtFuncWidget.show()
# Setting MAin Menu Widget for NOtes#
# self.NOTEmainMenuWidget = QWidget(self)
# self.noteMMWidgetLayout = QVBoxLayout()
# self.NOTEmainMenuWidget.setLayout(self.noteMMWidgetLayout)
# self.NOTEmainMenuWidget.setWindowTitle("Note Menu")
#
# self.NotemmButton1 = QPushButton("Admission", self)
# self.NotemmButton2 = QPushButton("Discharge", self)
# self.NotemmButton3 = QPushButton("Diag Testing", self)
# self.NotemmButton4 = QPushButton("Acute Visit", self)
# self.NotemmButton5 = QPushButton("Fall", self)
# self.NotemmButton6 = QPushButton("Med Review / Comp", self)
# self.NotemmButton7 = QPushButton("Coumadin", self)
# self.NotemmButton8 = QPushButton("Noncompliance", self)
# self.NotemmButton9 = QPushButton("Simple Note", self)
# self.noteMMWidgetLayout.addWidget(self.NotemmButton1)
# self.noteMMWidgetLayout.addWidget(self.NotemmButton2)
# self.noteMMWidgetLayout.addWidget(self.NotemmButton3)
# self.noteMMWidgetLayout.addWidget(self.NotemmButton4)
# self.noteMMWidgetLayout.addWidget(self.NotemmButton5)
# self.noteMMWidgetLayout.addWidget(self.NotemmButton6)
# self.noteMMWidgetLayout.addWidget(self.NotemmButton7)
# self.noteMMWidgetLayout.addWidget(self.NotemmButton8)
# self.noteMMWidgetLayout.addWidget(self.NotemmButton9)
# self.mdi.addSubWindow(self.NOTEmainMenuWidget)
# self.NOTEmainMenuWidget.show()
# self.NOTEMMButton2.clicked.connect(self.dcwindowFunc)
def admissionTool(self):
self.admitToolWidget = admitWindow()
self.mdi.addSubWindow(self.admitToolWidget)
self.admitToolWidget.show()
def COPDToolFunc(self):
self.copdToolWidget = COPDWindow()
self.mdi.addSubWindow(self.copdToolWidget)
self.copdToolWidget.show()
MDIWindow.copdcount = MDIWindow.copdcount + 1
def dcwindowFunc(self):
self.dcwindowWidget = DischargeWindow()
self.mdi.addSubWindow(self.dcwindowWidget)
self.dcwindowWidget.show()
def htnButton(self):
self.htnsubwidgets = QWidget(self)
self.htnMAinLayout = QHBoxLayout()
self.htnLeftLayout = QVBoxLayout()
self.htnRightLayout = QVBoxLayout()
##Adding secondary layours to main layouts##
self.htnMAinLayout.addLayout(self.htnLeftLayout)
self.htnMAinLayout.addLayout(self.htnRightLayout)
##Adding htnRightLayout widgets##
self.htnLabel1 = QLabel("Date of last HTN Med change", self)
self.htnDateEdit = QDateEdit(self)
self.htnDateEdit.setGeometry(QtCore.QRect(10, 30, 120, 45))
self.htnDateEdit.setObjectName("Med_change_dateEdit")
self.htnDateEdit.setDate(QtCore.QDate.currentDate())
self.htnDateEdit.setCalendarPopup(True)
self.htnQ2Label = QLabel("Med most recently changed?", self)
self.htnQ2LineEdit = QLineEdit()
self.htnQ3Label = QLabel("Most Recent bP Measurement", self)
self.htnQ3LineEdit = QLineEdit()
self.htnQ4Label = QLabel("Overall Bp Control?", self)
self.htnQ4Combobox = QComboBox()
self.htnQ4ComboboxList = ["Hypotension", "BP Well Controlled", "Some Hypertensive Episodes",
"Regular Hypertension"]
self.htnQ4Combobox.addItems(self.htnQ4ComboboxList)
self.htnq5Label = QLabel("Resident's current meds?", self)
self.htnq5LineEdit = QLineEdit()
self.htnCompleteButton = QPushButton("Complete", self)
self.htnCompleteButton.setMaximumWidth(75)
##Adding Widgets to Left Layout##
self.htnLeftLayout.addWidget(self.htnLabel1)
self.htnLeftLayout.addWidget(self.htnDateEdit)
self.htnLeftLayout.addWidget(self.htnQ2Label)
self.htnLeftLayout.addWidget(self.htnQ2LineEdit)
self.htnLeftLayout.addWidget(self.htnQ3Label)
self.htnLeftLayout.addWidget(self.htnQ3LineEdit)
self.htnLeftLayout.addWidget(self.htnQ4Label)
self.htnLeftLayout.addWidget(self.htnQ4Combobox)
self.htnLeftLayout.addWidget(self.htnq5Label)
self.htnLeftLayout.addWidget(self.htnq5LineEdit)
self.htnLeftLayout.addWidget(self.htnCompleteButton)
## Adding right widgets##
self.htntextedit = QTextEdit()
self.htntextedit.setMinimumWidth(200)
##Adding right widgets##
self.htnRightLayout.addWidget(self.htntextedit)
self.htnCompleteButton.clicked.connect(self.htnCompleteFunc)
self.htnsubwidgets.setLayout(self.htnMAinLayout)
self.mdi.addSubWindow(self.htnsubwidgets)
self.htnsubwidgets.show()
def htnCompleteFunc(self):
self.htnTotalList = [self.htnDateEdit.text(),self.htnQ2LineEdit.text(),self.htnQ3LineEdit.text(),self.htnQ4Combobox.currentText(),self.htnq5LineEdit.text()]
self.htntextedit.setText(f"The resient's most recent blood pressure med change ({self.htnTotalList[0]}) change was {self.htnTotalList[1]}. The residnet's most recent BP is {self.htnTotalList[2]}. The resdient is currently receiving {self.htnTotalList[4]}. Overall hypertension status: {self.htnTotalList[3]}")
def main():
app = QApplication(sys.argv)
font = QFont('Times', 10)
app.setFont(font)
mdiwindow = MDIWindow()
mdiwindow.show()
app.exec_()
if __name__ == '__main__':
main()ere
An example of one of my subwindowss is as follows:
from PyQt5 import QtCore
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWidgets import QMdiArea, QAction, QMdiSubWindow, QTextEdit
from Admission_Tool import *
from COPD_tool import *
class NOTEWindow(QWidget):
def __init__(self):
super().__init__()
self.notemdi = QWidget()
self.setStyleSheet('font-size: 10pt; font-family: Times;')
self.setStyleSheet("QPushButton{font-size: 10pt;}")
self.setStyleSheet("QLabel{font-size: 10pt;}")
self.notemdi.setMaximumSize(500,500)
#Setting MAin Menu Widget for this nested MDI#
self.NOTEmainMenuWidget = QWidget(self)
self.noteMMWidgetLayout = QVBoxLayout()
self.NOTEmainMenuWidget.setLayout(self.noteMMWidgetLayout)
self.NOTEmainMenuWidget.setWindowTitle("Note Menu")
self.mmButton1 = QPushButton("Admission", self)
self.mmButton2 = QPushButton("Discharge", self)
self.mmButton3 = QPushButton("Diagnostic Testing", self)
self.mmButton4 = QPushButton("Acute Visit", self)
self.mmButton5 = QPushButton("Fall", self)
self.mmButton6 = QPushButton("Med Review/Comp", self)
self.mmButton7 = QPushButton("Coumadin", self)
self.mmButton8 = QPushButton("Noncompliance", self)
self.mmButton9 = QPushButton("Weight Loss", self)
self.mmButton10 = QPushButton("Simple Note",self)
self.noteMMWidgetLayout.addWidget(self.mmButton1)
self.noteMMWidgetLayout.addWidget(self.mmButton2)
self.noteMMWidgetLayout.addWidget(self.mmButton3)
self.noteMMWidgetLayout.addWidget(self.mmButton4)
self.noteMMWidgetLayout.addWidget(self.mmButton5)
self.noteMMWidgetLayout.addWidget(self.mmButton6)
self.noteMMWidgetLayout.addWidget(self.mmButton7)
self.noteMMWidgetLayout.addWidget(self.mmButton8)
self.noteMMWidgetLayout.addWidget(self.mmButton9)
self.noteMMWidgetLayout.addWidget(self.mmButton10)
self.NOTEmainMenuWidget.show()
def main():
app = QApplication(sys.argv)
font = QFont('Times', 10)
app.setFont(font)
mdiwindow = NOTEWindow()
mdiwindow.show()
app.exec_()
if __name__ == '__main__':
main()

Python TypeError from the coad that I copy from another .py file

Here is the code that I copy from another .py file and I got a TypeError
#coding:utf-8
import serial
import sys
import time
import logging
class TestRemoteControl(object):
def __init__(self,com):
self.ser = serial.Serial(com,115200)
self.ser.bytesize = 8
self.ser.stopbits = 1
self.logger = logging.getLogger()
self.logger.setLevel(logging.INFO)
self.formatter = logging.Formatter('%(asctime)-25s - %(name)s - %(levelname)s - %(message)s')
self.ch = logging.StreamHandler()
self.ch.setLevel(logging.INFO)
self.fh = logging.FileHandler('Test.txt')
self.fh.setLevel(logging.INFO)
self.fh.setFormatter(self.formatter)
self.ch.setFormatter(self.formatter)
self.logger.addHandler(self.ch)
self.logger.addFilter(self.fh)
def start_esc(self):
self.logger.info("开启电机")
self.ser.write("####1")
def stop_esc(self):
self.logger.info("关闭电机")
self.ser.write("####1")
time.sleep(0.4)
self.ser.write("####1")
time.sleep(0.4)
self.ser.write("####1")
time.sleep(0.4)
def speed_up(self):
self.logger.info("电机加速")
self.ser.write("####3")
def speed_down(self):
self.logger.info("电机减速")
self.ser.write("####2")
def main():
logging.basicConfig(level=logging.DEBUG,
format = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt = '%a, %d %b %Y %H:%M:%S',
filename = 'myapp.log',
filemode = 'w')
print("please enter com num:")
a = raw_input()
temp_com = "com"+a
test_RC = TestRemoteControl(temp_com)
count = 1
max_count = int(raw_input('Please enter on-off counts'))
while count < max_count:
test_RC.start_esc()
# time.sleep(10)
# test_RC.speed_up()
time.sleep(2)
test_RC.stop_esc()
print "complete ",count," times "
time.sleep(1)
count += 1
if __name__ == "__main__":
main()
Here is the error, I don't kown why. Help me please.
TypeError:
unbound method init() must be called with TestRemoteControl instance as first argument (got nothing instead)
This code is OK.All the problem is the IDE "pycharm" that I can only run the unittest because I used the name "TestRemoteControl"

How to refer to the text entry widget`s input in a subprocess.call() in Python GTK?

How to refer to the text entry widget`s input in a subprocess.call() in Python GTK? App for calling bioinformatics tool from PyGTK:
#!/usr/bin/env python
import pygtk
pygtk.require('2.0')
import gtk
import subprocess
class EntryExample:
def enter_callback(self, widget, entry):
entry_text = entry.get_text()
print "Entry contents: %s\n" % entry_text
def entry_toggle_editable(self, checkbutton, entry):
entry.set_editable(checkbutton.get_active())
def entry_toggle_visibility(self, checkbutton, entry):
entry.set_visibility(checkbutton.get_active())
def __init__(self):
# create a new window
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_size_request(200, 100)
window.set_title("GTK Entry")
window.connect("delete_event", lambda w,e: gtk.main_quit())
vbox = gtk.VBox(False, 0)
window.add(vbox)
vbox.show()
entry = gtk.Entry()
entry.set_max_length(50)
entry.connect("activate", self.enter_callback, entry)
entry.set_text("Insert")
entry.insert_text(" SRA accession number", len(entry.get_text()))
entry.select_region(0, len(entry.get_text()))
vbox.pack_start(entry, True, True, 0)
entry.show()
hbox = gtk.HBox(False, 0)
vbox.add(hbox)
hbox.show()
# Create a new button for running Linux Shell script
buttonscript = gtk.Button(label="Download", stock=None)
# Connect the "clicked" signal of the button to the function
buttonscript.connect("clicked", runlinuxshell )
vbox.pack_start(buttonscript, True, True, 0)
buttonscript.set_flags(gtk.CAN_DEFAULT)
buttonscript.grab_default()
buttonscript.show()
button = gtk.Button(stock=gtk.STOCK_CLOSE)
button.connect("clicked", lambda w: gtk.main_quit())
vbox.pack_start(button, True, True, 0)
button.set_flags(gtk.CAN_DEFAULT)
button.grab_default()
button.show()
window.show()
def runlinuxshell ():
subprocess.call('$i=len(entry.get_text()) # Error is here
echo $i
./fastq-dump --split-files $i -v')
def main():
gtk.main()
return 0
if __name__ == "__main__":
EntryExample()
main()
How to pass text input from a widget into the suprocess.call()?
Is there any good example on how to call bioinformatics linux tools in PyGTK?
disclaimer: the sample uses pygobject with introspection and not pygtk which is deprecated for years and should not be used in new code.
disclaimer 2: the sample can be greatly improved to say the least, it's just an adaption of your original script.
You probably would do some like the following:
import gi
from gi.repository import Gtk
import subprocess
class EntryExample:
def __init__(self):
window = Gtk.Window()
window.set_size_request(200, 100)
window.set_title("GTK Entry")
window.connect("delete_event", Gtk.main_quit)
vbox = Gtk.VBox(False, 0)
window.add(vbox)
self.entry = Gtk.Entry()
self.entry.set_max_length(50)
self.entry.set_text("SRA accession number")
vbox.pack_start(self.entry, True, True, 0)
buttonscript = Gtk.Button(label="Download", stock=None)
buttonscript.connect("clicked", self.runlinuxshell)
vbox.pack_start(buttonscript, True, True, 0)
button = Gtk.Button(stock=Gtk.STOCK_CLOSE)
button.connect("clicked", Gtk.main_quit)
vbox.pack_start(button, True, True, 0)
window.show_all()
def runlinuxshell (self, widget):
mylen = len(self.entry.get_text())
# Here you will execute your subprocess with mylen
def main(self):
Gtk.main()
if __name__ == "__main__":
sub = EntryExample()
sub.main()

Double buffering in Jython

recently I started learning Jython and now I have rather simply problem. I would like to improve quality of my animation. Unfortunately I don't know how to add double buffering to my applet . Could you help me?
Best regards!
from javax.swing import JToolBar
from javax.swing import JButton
from javax.swing import JFrame
import time
from java import awt
from java.awt import BorderLayout
class Canvas(awt.Canvas):
u"Canvas - drawing area"
def __init__(self,winSize = 400):
self.play = False
self.background=awt.Color.black
self.winSize = winSize
self.l = 0
def playSim(self, play):
if play == True:
self.play = True
self.repaint()
else: self.play = False
def paint(self, g):
g.fillRect(50, int(self.winSize/4), self.l, int(self.winSize/2))
if self.l < self.winSize: self.l += 1
else: self.l = 0
time.sleep(0.02)
if self.play == True: self.repaint()
class Example(JFrame):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
winSize = 600
toolbar = JToolBar()
self.playButton = JButton("Start", actionPerformed=self.playButtonPress )
toolbar.add(self.playButton)
self.add(toolbar, BorderLayout.NORTH)
self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
self.setSize(winSize, winSize)
self.setResizable(False)
self.setLocationRelativeTo(None)
self.setVisible(True)
self.canvas = Canvas(winSize)
self.getContentPane().add(self.canvas)
self.setTitle("TEST")
self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
def playButtonPress(self, e):
if self.playButton.getLabel() == "Start":
self.canvas.playSim(True)
self.playButton.setLabel("Stop")
else:
self.playButton.setLabel("Start")
self.canvas.playSim(False)
if __name__ == '__main__':
Example()
I solved my recent problem:
from javax.swing import JToolBar
from javax.swing import JButton
from javax.swing import JFrame
import time
from java import awt
from java.awt import BorderLayout
class Canvas(awt.Canvas):
u"Canvas - drawing area"
def __init__(self,winSize = 400):
self.play = False
self.background=awt.Color.black
self.winSize = winSize
self.l = 0
self.bi = BufferedImage(winSize, winSize, BufferedImage.TYPE_INT_RGB)
self.offScreenGraphics = self.bi.getGraphics()
def playSim(self, play):
if play == True:
self.play = True
self.repaint()
else: self.play = False
def paint(self, g):
self.offScreenGraphics.fillRect(50, int(self.winSize/4), self.l, int(self.winSize/2))
if self.l < self.winSize: self.l += 1
else: self.l = 0
g.drawImage(self.bi, 0, 0, None)
time.sleep(0.02)
if self.play == True: self.repaint()
class Example(JFrame):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
winSize = 600
toolbar = JToolBar()
self.playButton = JButton("Start", actionPerformed=self.playButtonPress )
toolbar.add(self.playButton)
self.add(toolbar, BorderLayout.NORTH)
self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
self.setSize(winSize, winSize)
self.setResizable(False)
self.setLocationRelativeTo(None)
self.setVisible(True)
self.canvas = Canvas(winSize)
self.getContentPane().add(self.canvas)
self.setTitle("TEST")
self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
def playButtonPress(self, e):
if self.playButton.getLabel() == "Start":
self.canvas.playSim(True)
self.playButton.setLabel("Stop")
else:
self.playButton.setLabel("Start")
self.canvas.playSim(False)
if __name__ == '__main__':
Example()
Now I've another(rather trivial) problem:
How can I make from this python file *the class file* which would be ready to publish it on website as an applet?