[HOWTO] Program using Python


Recommended Posts

Lesson #2

In Lesson #1 we've already seen how easy it is to make simple CLI programs that would print messages on the console, and a simple example of a way to display a message on screen using a graphical toolkit. This lesson will explore the graphical toolkits available for python, with special approach to one of the most advanced toolkits available, QT.

Part 1: Joke reader.

In this part we are going to make a simple program that reads a text file and display its contents on screen. We will be making something very (questionably) useful, a joke reader.

post-52106-1228771871.png

  • Download the file attached;
  • Extract it to a directory;
  • Open "joker.py" with your editor.

neowin_joker.zip

The imports.

In this part of the code we import the PyQt4 modules. We are using the "from package.component import *" so we can save on the typing, like it was referred before. If the libraries aren't available then an error message is printed informing about the missing libraries and the program is terminated.

#Import the PyQt4 modules. Exit if not found.
try:
	from PyQt4.Qt import *
	from PyQt4.QtCore import *
	from PyQt4.QtGui import *
except:
	print "Failed to load QT libraries. Please intall PyQt4 first."
	sys.exit(1)

Here we import our jokes module. This module contains an array with our jokes, so we can use and cycle between them later. If the module cannot be imported then the program gets terminated here.

#Import the jokes module. Exit if not found.
try:import jokes
except:
	print "Could not find the jokes."
	sys.exit(1)

Build the widgets.

This is the part where we build our widgets. In this program we are only using a simple text browser and 3 buttons. Those buttons get connected to a function and when the clicked signal is emitted that same function is called. This is explained in the QT manual and should be consulted first before starting to program using QT. Also the "Qt's Main Classes" page is of most importance. In there all the QT components are explained in detail and the way they can be used. It's the API reference page for QT.

class Neowin_Jokster(QMainWindow):
	def __init__(self):
		QMainWindow.__init__(self)

		print "Starting application"


		self.textBrowser = QTextBrowser(self)
		self.textBrowser.setGeometry(QRect(0,0,511,251))
		self.textBrowser.setObjectName("textBrowser")

		self.buttonPrev=QPushButton(self)
		self.buttonPrev.setText("&Previous")
		self.buttonPrev.setGeometry(QRect(30,255,90,32))

		self.buttonNext=QPushButton(self)
		self.buttonNext.setAutoDefault(1)
		self.buttonNext.setDefault(1)
		self.buttonNext.setText("&Next")
		self.buttonNext.setGeometry(QRect(130,255,65,32))

		self.buttonExit=QPushButton(self)
		self.buttonExit.setText("&Exit")
		self.buttonExit.setGeometry(QRect(430,255,65,32))

		self.connect(self.buttonPrev,SIGNAL("clicked()"),self.prev_joke)
		self.connect(self.buttonNext,SIGNAL("clicked()"),self.next_joke)
		self.connect(self.buttonExit,SIGNAL("clicked()"),self.buttonExit_clicked)

		self.setMinimumSize(QSize(510,290))
		self.setMaximumSize(QSize(510,290))
		try:self.move(QApplication.desktop().width() / 4,QApplication.desktop().height() / 4)
		except:pass


		self.get_jokes()

The jokes.

These two functions are used to cycle between the jokes. They are executed when the "previous" and "next" buttons are pressed, respectively.

	def prev_joke(self):
		"""Previous joke"""
		global curr_joke

		#Cycle between the jokes.
		if curr_joke >= 1:curr_joke -= 1
		else:curr_joke=len(jokes.neowin_jokes)-1
		self.textBrowser.setText( str(jokes.neowin_jokes[curr_joke]) )

	def next_joke(self):
		"""Next joke"""
		global curr_joke

		#Cycle between the jokes.
		if curr_joke <= len(jokes.neowin_jokes)-2:curr_joke += 1
		else:curr_joke=0
		self.textBrowser.setText( str(jokes.neowin_jokes[curr_joke]) )

Quit it.

This function is executed when our "Exit" button is pressed. It's used to exit...

	def buttonExit_clicked(self):
		"""Exit"""
		print "Exit"
		self.close()

Calling and Looping.

This gets executed when the application is invoked. It's used to call our class above so the widget can be created. It also creates a loop so the window executes until it quits. We also set the window title as "neowin.net Jokes Reader". One important part in QT widgets is the "show()". If this wasn't passed to the window nothing would show up.

if __name__ == "__main__":
	app = QApplication(sys.argv)
	f = Neowin_Jokster()
	f.setWindowTitle("neowin.net Jokes Reader")
	f.show()
	sys.exit(app.exec_())

To run this program just open a terminal on the directory where you have your python file and run it by typing on the terminal:

python joker.py

Learning tips:

Add some more widgets to the window.

This completes this part of lesson #2.

_____________________________________________________________

Part 2: Recalculate.

In our previous program we've already seen how to make a simple graphical program, with simple widgets connected to functions that would perform simple tasks. In this tutorial we are going to explore that subject in a bit more detail.

We will be making a calculator (yes another), with a simple graphical interface. 1337 Calculator in a bit over 500 lines of code:

post-52106-1228927456.png

  • Download the file attached;
  • Extract it to a directory;
  • Open "1337_calculator.py" with your editor.

1337_calculator.zip

Declaring globals.

In this part of the code we are declaring our three global variables (palette, pallete2 and var). The variable "var" is in fact a Dictionary, this is one of the most useful datatypes from python and an important one to understand.

palette = palette2 = None

# We start by storing our values inside dictionaries. Dictionaries are nice, they can store a big ammount of variables

# indexed by keys, which allow them to be kept editable to humans (and dolphins too, in a near future).

var={ 'calc_cleared':False, 'calcon_op':False, 'calcurr_op':None, 'calclast_val':None, 'calc_return':int }

Create widgets.

This is our class for creating the window and populating it with all the widgets. Here all the connections from the widget to the functions are made. Analyze the code to see how the individual widgets are connected.

class Leet_Calculator(QMainWindow):
	def __init__(self):
		QMainWindow.__init__(self)
(...)

Connectors.

These are the small functions to where we have connected our widgets. They get executed when a button in our calculator is pressed. Each one of them will then call our "Abacus" class with a parameter so that the specific action, intended by the key press event, occurs.

#All Clear
	def buttonCE_clicked(self):
(...)

Quit it.

Our "off" button used to exit the program.

#OFF
	def buttonOff_clicked(self):
(...)

Calculations.

This is our calculations class. A class that analyses an "input" and makes the calculations of what to display. Notice how the "__init__" function is written. It's the "__init__" that is responsible for all that will get executed.

#Class used to make our key pressing instructions and calculations

class Abacus:
	def __init__(self,widget,key):
		self.key=key

		if self.key=="CE" or self.key=="C":self.abacusClear(widget)
		elif self.key=="+" or self.key=="-" or self.key=="*" or self.key=="/":self.abacusCalc(widget)
		elif self.key=="=":self.abacusResult(widget)
		else:self.abacusSlide(widget)
(...)

Style.

This function is used to style our buttons, we create some nice palettes so we can then apply those to our buttons. Nothing too advanced here.

#Palette builder
class PaletteBuilder:
(...)

Calling and Looping.

This gets executed when the application is invoked. It's used to call our widget creator class so that the window can be created. It also creates a loop so the window executes until it quits. We also set the window title as "1337 calculator" and call the palette builder.

if __name__ == "__main__":
	app = QApplication(sys.argv)
	PaletteBuilder()
	f =Leet_Calculator()
	f.setWindowTitle("1337 calculator")
	f.show()
	sys.exit(app.exec_())

To run this program just open a terminal on the directory where you have your python file and run it by typing on the terminal:

python 1337_calculator.py

Learning tips:

Make a more advanced calculator.

This completes this part of lesson #2.

Edited by Lechio
Link to comment
https://www.neowin.net/forum/topic/707760-howto-program-using-python/
Share on other sites

  • 2 weeks later...
How Easy to learn is python?

Python is a very easy to learn language.

Some minutes dispensed reading the manual is all it takes to start making basic scripts. Compared to other "object-oriented languages" I personally consider it to be one of the easiest ones to learn. Yet, advanced programming can also be done with python. It's a good language for someone who wants to start programming and, as it does not need to compile, it's also a very good language to implement fast programming solutions.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Would you please fix your graphics. They are outdated and don't fit the article.
    • The Light of Life? We actually do glow till our Death, study finds by Sayan Sen Image by Rafael Rendon via Pexels A study by researchers at the University of Calgary has found that living organisms produce an extremely faint light known as ultraweak photon emission, and that this glow appears to drop significantly after death. The research was published in the Journal of Physical Chemistry in April 2025 and quickly drew widespread attention, leading to more than 200 news stories about the findings. Ultraweak photon emission (or UPE), sometimes called biophoton emission, refers to tiny amounts of light released by living cells as a result of normal biological activity. A photon is the basic particle of light, and researchers say every living system examined so far, including plants and animals, has been found to emit these photons. The glow is far too faint to be seen by the human eye. “I suppose it has a little to do with people being reminded of auras,” says Dr. Christoph Simon, PhD, one of the authors of the study and a professor in the Department of Physics and Astronomy in the Faculty of Science. “It is a fact that living beings glow. It’s a very weak glow, but it’s there and visible with very sensitive cameras.” According to the study, the light involved is extremely weak, ranging from 10 to 1,000 photons per square centimetre per second across a spectral range of 200 to 1,000 nanometres. For comparison, a nanometre is one-billionth of a metre and is commonly used to measure wavelengths of light. Detecting emissions at such low levels requires highly specialized equipment. To study the phenomenon, researchers used electron-multiplying charge-coupled device (EMCCD) and charge-coupled device (CCD) cameras. These imaging systems are designed to detect extremely small amounts of light, including individual photons, while minimizing background noise. The technology allowed researchers to capture signals that would otherwise be impossible to observe. The team worked with the Human Health Therapeutics Research Centre at the National Research Council of Canada (NRC) in Ottawa to examine photon emissions in mice. Researchers took two-hour exposure images of the animals before and after death and compared the results. “We saw that the level of light that they emit – this biophoton glow – is distinctly different between living and dead animals,” says Dr. Daniel Oblak, PhD, an associate professor in Physics and Astronomy and the corresponding author of the study. The images showed a clear decrease in photon emissions after death across the entire body of each mouse. According to the researchers, this provided direct evidence that living and dead tissue produce different levels of ultraweak photon emission. “It’s a very small amount and it’s, of course, very tricky to detect,” Oblak says. The study grew out of discussions between Simon, whose research interests include quantum biology, and Oblak, whose work focuses on detecting light for quantum communication experiments. Quantum biology is a field that explores whether processes described by quantum physics, which studies matter and energy at very small scales, may also play a role in living systems. “Since I work as a quantum physicist on light detection for quantum communication, I thought that experimentally we have a lot of the tools to be able to detect the light,” Oblak explains. The researchers also investigated UPE in plants and found that the light changed in response to stress. When plants were exposed to higher temperatures or physically injured, their photon emissions increased. Chemical treatments also affected the glow. Among the substances tested, the local anesthetic benzocaine produced the strongest emission response when applied to injured plant tissue. These findings suggest that ultraweak photon emission is closely linked to biochemical and metabolic activity inside living organisms. Metabolism refers to the chemical reactions that allow cells and organisms to stay alive and function. Because these reactions change when an organism experiences stress, injury or disease, researchers believe UPE may provide a way to monitor those changes. The researchers stress that the glow is a physical and biological phenomenon, not a metaphysical one. Oblak says more research is needed to understand exactly how the light is produced and what information it may reveal about the condition of living tissue. “We must understand what that is to figure out what’s happening,” he says. “If we can understand how that relates to certain influences on the body – stress, diseases – then that could be used as a diagnostic tool.” The researchers believe the technique could eventually help scientists study health and disease without invasive procedures. Because UPE can be measured without adding dyes, markers or labels, it may offer a way to monitor whether tissue is healthy, damaged or alive. In plants, it could help researchers better understand how organisms respond to injury, heat and other forms of stress. While the work is still in its early stages, the study demonstrates that ultraweak photon emission imaging can provide a non-invasive and label-free way to observe biological activity. Researchers say the approach could become a useful tool for studying vitality, stress responses and other important processes in both animals and plants. Source: University of Calgary, ACS publication This article was generated with some help from AI and reviewed by an editor. Under Section 107 of the Copyright Act 1976, this material is used for the purpose of news reporting. Fair use is a use permitted by copyright statute that might otherwise be infringing.
    • Damn, I loved this show back in the day.  
    • Rufus 4.15.2393 Beta 2 by Razvan Serea Rufus is a small utility that helps format and create bootable USB flash drives, such as USB keys/pendrives, memory sticks, etc. Despite its small size, Rufus provides everything you need! Oh, and Rufus is fast. For instance it's about twice as fast as UNetbootin, Universal USB Installer or Windows 7 USB download tool, on the creation of a Windows 7 USB installation drive from an ISO (with honorable mention to WiNToBootic for managing to keep up). It is also marginally faster on the creation of Linux bootable USBs from ISOs. A non-exhaustive list of Rufus supported ISOs is available here. It can be especially useful for cases where: you need to create USB installation media from bootable ISOs (Windows, Linux, UEFI, etc.) you need to work on a system that doesn't have an OS installed you need to flash a BIOS or other firmware from DOS you want to run a low-level utility Rufus 4.15.2393 Beta 2 changelog: Add RISC-V 64 support to UEFI:NTFS Improve the guards for using the "silent" option Improve the ability to cancel during write retries Improve progress reporting for compressed image extraction Fix unrestricted XML entity expansion and integer overflow in ezxml parser (courtesy of @esadowski4) [GHSA-55r2-34wg-8mv9] Fix "silent" Windows installation failing at 75% in most cases [#2960] Fix a crash during boot when using UEFI:NTFS on Snapdragon X based ARM64 platforms [#2934] Fix the first WUE option always being checked by default [#2965] Fix an infinite loop when using Windows ISOs that contain multiple WIMs Fix "Enable runtime UEFI media validation" checkbox not always being properly enabled Other WUE improvements/fixes for OneDrive removal and username validation (with thanks to @christian8641) [#2984, #2991] Download: Rufus 4.15 Beta 2 | 1.9 MB (Open Source) Links: Rufus Home Page | Project Page @GitHub | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • One Year In
      hhgygy earned a badge
      One Year In
    • One Month Later
      AMV earned a badge
      One Month Later
    • Week One Done
      AMV earned a badge
      Week One Done
    • Collaborator
      ryansurfer98 went up a rank
      Collaborator
    • One Month Later
      Eurosoft10 earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      515
    2. 2
      +Edouard
      171
    3. 3
      PsYcHoKiLLa
      83
    4. 4
      Steven P.
      74
    5. 5
      Michael Scrip
      72
  • Tell a friend

    Love Neowin? Tell a friend!