[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

    • Microsoft finally admits its default Windows 11 25H2, 24H2 action broke key legacy component by Sayan Sen Microsoft last week released Windows 11 KB5094126 and KB5093998 as the latest Patch Tuesday updates. Following that the company also published the accompanying dynamic updates under KB5094149, KB5095971, and KB5094156. So far the company has acknowledged two known issues that have popped up after the release which include bugged-out Office apps as well as the Recycle Bin; though there could be more at play too. Speaking of bugs and issues, Microsoft seems to have finally acknowledged a problem that probably has been around for close to a year. That's because back in July of 2025 the company made a default change to the latest Windows 11 versions, wherein it switched to JScript9Legacy on Windows 11 24H2 and later releases. Hence following the release of version 25H2 in October 2025, JScript9Legacy also remained default-enabled. As a result there has been a compatibility issue ever since then. For those wondering, by switching to JScript9Legacy Microsoft intended to improve the security of modern Windows PCs by reducing vulnerabilities tied to legacy scripting like cross-site scripting (XSS), among others. XSS exploits can allow cyber-attackers to attach malicious code onto legitimate websites and use them to execute the code when a potential victim loads such a website. Hence the new JScript9Legacy engine enforced stricter execution policies and improved object handling, which should help mitigate such attacks. Microsoft today has published a new support article detailing the problem. Neowin spotted it while browsing. The company says that JScript global definitions and execution context may fail to persist across scripts, potentially breaking older dependent apps and web-based components that relied on this legacy behavior. In the article Microsoft has confirmed that the issue stems from its move away from the older jscript9.dll engine in favor of jscript9legacy.dll. As mentioned above, while the newer engine was designed to address vulnerabilities and strengthen security it also changes how JScript handles execution context. As a result functions and definitions loaded by one script could no longer remain available to subsequent scripts once execution ended. The company notes that some applications worked correctly on earlier Windows versions because the older JScript engine automatically retained global definitions and execution state between scripts. Under the newer model though that behavior is disabled by default causing certain legacy workloads and polyfill-dependent scripts to fail. Microsoft says it addressed the problem via the KB5077241 update though the fix had not been enabled automatically in the following updates. As such admins must explicitly turn on persistent JScript execution context using a Registry setting that the tech giant shared today. The configuration can be applied to individual processes or system-wide through the FEATURE_ENABLE_PERSISTENCE registry key. The steps have been outlined below: Run the following command to create the feature control registry key: reg add "HKLM\Software\Policies\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_ENABLE_PERSISTENCE" Under this key, create a new DWORD (32-bit) value. Configure the value as follows: To enable persistence for specific processes only: Set the value to 1 for each target process name. To enable persistence for all processes: Add * as the key name and set its value to 1. You can find the official support article here on Microsoft's website.
    • The possibility that milk gathers back into a glass implies that gravity can be 'reversed'.
    • VidCoder 12.20 by Razvan Serea  VidCoder is a DVD/Blu-ray ripping and video transcoding application for Windows. It uses HandBrake as its encoding engine. Calling directly into the HandBrake library gives it a more rich UI than the official HandBrake Windows GUI. VidCoder can rip DVDs but does not defeat the CSS encryption found in most commercial DVDs. You’ll need the NET 8 Desktop Runtime. If you don’t have it, VidCoder will prompt you to download and install it. The Portable version is self-contained and does not require any .NET Runtime to be installed. You do not need to install HandBrake for VidCoder to work. Feature list: Multi-threaded MP4, MKV containers Completely integrated encoding pipeline: everything is in one process and no huge intermediate temporary files H.264, H.265, MPEG-4, MPEG-2, VP8, Theora video Hardware-accelerated encoding with AMD VCE, Nvidia NVENC and Intel QuickSync AAC, MP3, Vorbis, AC3, FLAC audio encoding and AAC/AC3/MP3/DTS/DTS-HD passthrough Target bitrate, size or quality for video 2-pass encoding Decomb, detelecine, deinterlace, rotate, reflect, chroma smooth, colorspace filters Powerful batch encoding with simultaneous encodes Customizable Pickers to automatically pick audio and subtitle tracks, destination, titles and more Instant source previews Creates small encoded preview clips Pause, resume encoding VidCoder 12.20 changes: Updated HandBrake core to 1.11.2. Download: VidCoder 12.20 | 47.0 MB (Open Source) Download: Portable VidCoder 12.19 | 89.3 MB Link: VidCoder Home Page | Github | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Week One Done
      Jordan Smith earned a badge
      Week One Done
    • Reacting Well
      BizSAR earned a badge
      Reacting Well
    • First Post
      AndreaB earned a badge
      First Post
    • Week One Done
      Huge Trailer earned a badge
      Week One Done
    • Week One Done
      Classifyskilleducation earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      590
    2. 2
      +Edouard
      185
    3. 3
      PsYcHoKiLLa
      76
    4. 4
      Michael Scrip
      73
    5. 5
      Steven P.
      66
  • Tell a friend

    Love Neowin? Tell a friend!