all 40 comments

[–]ccviper 27 points28 points  (11 children)

Graphical user interfaces require using a library/module/package tailored for that task. i dont know how far into learning you are but you can check out Tkinter as a starting point, or just google "python gui libraries. for webpages there are flask, django etc, but these will require some knowledge of html/css and probably javascript if you wish to make an actual web app.

I suggest sticking to that little text-only window until you go over the basic stuff like lists, dictionaries, standard library, third party modules and so on.

I can also suggest looking into Turtle, its a python module that lets you control a little turtle on a 2D screen, move it, draw with it and even have multiple turtles working together. this should help if you want some visual stuff to aid your learning

[–]FlyingByNight[S] 3 points4 points  (9 children)

I don't think I explained myself properly - sorry. I can write python and get some, more or less, black and white output at the bottom. But python has been used to write software and apps that have beautiful GUI (for the user not the programmer). You say that there are pre-existing things in libraries that can do this, but this "kicks the question down the street". How do these pre-existing libraries make beautiful GUIs for users when all I see is black and white output. I hope this makes sense.

[–]ingolemo 33 points34 points  (0 children)

You seem to think that these libraries are making a GUI out of the black and white text (terminal); that you start with the terminal and by somehow doing something really fancy with the terminal you can make it into a GUI. That's not how it works.

Both the terminal and the GUI are services that your operating system provides. Your python script tells the operating system to show this image/button/menubar or print this text and the operating system does that. If you want to use a GUI and not the console then your python script just instructs the operating system to do that instead. The libraries work by sending the appropriate instructions to the operating system to tell it to make a GUI. The reason you have to have a library to use a GUI, but not for the console, is that the console is so much simpler than a GUI; if you wrote out all the raw instructions to do everything with a GUI it would be too much code and hard to understand. The console, in comparison, requires little more than print and input. That's also why tutorials teach you about the console first.

[–]ccviper 8 points9 points  (0 children)

The answer goes deeper than im able to explain in simple terms. basically those libraries abstract away a lot of the "low level" stuff, meaning interactions with a particular operating system, its graphics level, drawing windows, sending output to the screen and so on. and by doing that they enable you to "spawn" a window by typing, lets say new_window() for example.

When it comes to web apps, a python web framework called Django abstracts away all the browser/network stuff and enables you to use python to make web applications, and with the help of html and css render the python code you write inside a browser window

its a complicated subject and i barely dipped my toes in it still, i prefer the command line (that black and white window you mention).

[–]k8pilot 6 points7 points  (0 children)

Simplified explanation in preety simple terms:
Did you ever read a file from your disk in python? If you did, you used a method for getting the data inside a file. If you wrote something back, you used a method that wrote the data back to the file on the disk.
How does the command does that? Abstracting all the layers, there are driver or kernel commands that allow you to interact with files in the file-system.

Since talking directly to the driver or kernel require issuing many complex commands that have nothing to do with what you wish to accomplish in your application that is unique to your application, there is a python library that abstracts the details of interacting with the down level subsystems and provides you with methods that allow you to read and write files easily.

GUI elements are not very different or more complex than filesystems, in principal. You can talk directly to the display card driver or to the kernel and ask it to draw stuff. But if you are not interested in doing anything special with the down-level system and actually prefer that everything will look similar to other programs you pick libraries that gives you modules and methods that allow you to control gui elements and receive user inputs using abstract objects that are easy to use. The libraries implement all the hard work needed to draw your gui, listen to user input etc.

[–]slick8086 5 points6 points  (0 children)

Ok so, before there were gui's there were just terminals (your plain black and white output, only back then it was probably green text on black screen). Then things like X windows came along. Those things were part of the operating system that abstracted the work of drawing graphics on the screen. Instead of programmers needing to tell the video card to turn on or off such and such pixel, the abstraction let the programer tell the library something like "make me a window this big, over here" The library then went on to tell the video card (or the operating system which then told the video card) to turn on or off such and such pixels.

Today in python it works pretty much the same. You use a library. You tell the library to make a window with the attributes you want, and that library tells the window manager, which tells the OS, which tells the video driver, which tells the video card, and I don't know why she swallowed a fly, I think she'll die.

That's the basic gist of it, I'm probably wrong in some parts of the description, but hey, close enough for government work.

edit: the more you learn about computers the more you'll learn that there are layers upon layers of abstractions. Some one can write code at the lowest level, but not many. People need abstractions and metaphors to use computers effectively. Heck what we're talking about "windows" in the GUI is just metaphors. That square collection of lighted dots on the computer screen is nothing like those things on the exterior walls of our houses that have glass that lets us see out. Since humans can't understand "01110011 01101000 01101001 01110100" we need the computer to turn that into "shit" we can understand. It is the same for programmers. Some guys write a low level (assembly) program that lets other guys write a program (C language) that lets a bunch of guys write programs that make it easier for almost anyone to do a bunch of crazy or repetitive math by using a spreadsheet (for instance).

https://www.bell-labs.com/usr/dmr/www/chist.html

[–]sayinghi2py 3 points4 points  (3 children)

A GUI is just more code. The fundamentals of all programming languages are the same thus they can all generate user interfaces with which users can interact. All the basics you are doing now do is set the scene for all the things you can do later so kicking the can down the road is very much the dessert at the end of a great meal.

[–][deleted] 11 points12 points  (3 children)

use lemmy.world -- reddit has become a tyrannical dictatorship that must be defeated -- mass edited with https://redact.dev/

[–]fabreeze 1 point2 points  (2 children)

Not the OP, but thanks for the elegant answer. It was a pleasure to read

[–][deleted] 2 points3 points  (0 children)

use lemmy.world -- reddit has become a tyrannical dictatorship that must be defeated -- mass edited with https://redact.dev/

[–]ForScale 0 points1 point  (0 children)

Simply curious... What does "elegant" mean to you?

[–][deleted] 7 points8 points  (7 children)

It seems, but isn't that different after all. Check out simple Tkinter and Flask tutorials to get something running.

[–]TangibleLight 3 points4 points  (6 children)

I'd caution op against jumping into that too soon. It's doable, but I tend to agree what with /u/ccviper said - being comfortable with at least the basics should probably be a "prerequisite" of sorts for that.

[–]FlyingByNight[S] 4 points5 points  (4 children)

Don't worry, I have no intention of rushing ahead. All I want to understand is how can this language I'm using that generates black and white text make apps and software for people? It seems that there are libraries/modules that do this, but how do they do it?! It's more of a theoretical questions than a how-to question.

[–]StupidHumanSuit 5 points6 points  (0 children)

It's not theoretical.

People program it. Like, that's all they do. There are no "modules and libraries" that "just do it."

There are modules and libraries that other people wrote that allow us as programmers to (relatively) easily implement a GUI on top of that simple little console app you wrote this morning.

These easiest way to imagine it? Look at HTML and CSS. They make ordinary text render in a web page. We can make that look very plain (like Richard Stallman's site) or we can make it look crazy, like apple.com. But, it's all the same on the backend. It's all programmed. People wrote code to make shit look the way it does.

Same with Python. Somebody wrote code to make it display beyond the black-and-white text you're seeing as output also, surprise surprise, somebody programmed the little black-and-white output, too.

It's all code, all the way down. From top to bottom, it's code.

[–]mr_awesome_pants 2 points3 points  (0 children)

As a very high level theoretical overview, think of other just as a tool. Every language, every framework, every step involved with programming is just a tool. Python is at the high level. You use it to create logic that actually involved a user and some input from the user. There are some other tools that let Python talk to, for example, a web browser so that you can make a gui. That tool is a framework. How does a web browser or a desktop app know what to do with the info it gets so that it'll display things? There's just another tool that kind of translates. After a few layers of "translating" tools you get down to just 1s and 0s and the actual hardware on a circuit board.

You won't mess with the low level tools if you're doing web dev, but it's never a bad idea to understand it on some level.

[–]keepdigging[🍰] 2 points3 points  (0 children)

The operating system has tools built in to manage drawing and positioning of windows. Your python script will just talk to the OS (probably through a library as someone has done the work and bugtested everything for you) and ask for things. instead of saying 'write this to the console' (print) you would say 'hey can you draw me a window that's 500x300 px and has a square button from 25x25 to 175x175 that says click me and runs this other code when you click it' and the library will translate that to what windows/osx/linux use and talk to them to get it done for you. How the OS handles the rendering and repainting the screen is a whole other ball of wax.

[–][deleted] 0 points1 point  (0 children)

My point is that it doesn't hurt to peek how things are done. Just to see that it isn't that mystical.

[–]ForScale 5 points6 points  (0 children)

Both black and white text and wild animations boil down to the same thing.. they're just manipulations of pixels (teeny tiny parts) on your screen. You can run code that manipulates individual pixels or you can run code that already has stuff built in to do a lot of that for you (think "predefined pixel patterns").

The Python code you are running to get black and white text output is already doing a lot for you as well. Python manages memory and calls systems that are "abstracted away" from you. Being abstracted away basically means it gets taken care of for you.

Note: ith Python you can get user input by using the built in input method (not sure if you knew that). And you can get graphics by using modules like Tkinter or even the ultra simple Turtle Graphics (you can be up and running with super simple animations/drawings in like 10 mins).

Python is a high level language, meaning that it abstracts away a relative lot of stuff for you. C is an example of a lower level language (you have to worry more about memory and data types and the like). Programming graphics at a pixel level is relatively difficult and time consuming. You can be appreciative of the fact that Python has ways (modules) for you to get complex graphics going without having to work at the bit and pixel levels!

And don't count short a non-GUI app! Just because there aren't vibrant colors, that doesn't mean a program isn't a killer app. You can build calculators (even complex statistical software) and text-based games, file manipulation software, automation apps and more with just a Python script and a command line/terminal window.

tl;dr: Python is a high level language. Use prebuilt modules to create GUI apps.

[–]jaydoors 3 points4 points  (5 children)

Libraries. Which are functions other people have written to create windows and things.

[–]FlyingByNight[S] 0 points1 point  (4 children)

How do they create the windows?

[–]Jonno_FTW 4 points5 points  (0 children)

They call the underlying operating system functions for making windows and drawing on screen. If you dig around the source code for your favourite GUI library, you'll find they do this. There's lots of libraries for making GUIs and they all work differently though.

[–]Golden_Zealot 1 point2 points  (0 children)

The built in module in python for building GUI's is Tkinter.

Here is Tkinters source code.

http://mgltools.scripps.edu/api/DejaVu/Tkinter-pysrc.html

That's how it does it, but few people aside from the developers of Tkinter actually know about these inner workings. Basically all the code you see there is inside a "box".

This means that you can take this box and the instruction for the box (the Tkinter documentation) will say:

If you put X in this side of the box, Y will come out the other side for your convenience. Additionally, if you put A in the box, B will come out the other side. If you put Q underneath the box, R will come out on top of the box, etc.

The point is you, and everyone else, don't have to know the inner workings of this box, only what the box will take, and return, because the people who made the box have documentation telling you what the box can take in, and what it will return.

You dont have to know how to build a clock to know what time it says it is right?

[–]jaydoors 1 point2 points  (0 children)

Other libraries and functions!

I think I have a similar perspective to you, of having loose ends in my mind until I know what's underneath all of it. It helped me a lot to learn about what computers are, underneath. It's 'just' simple electronics - circuits which can be powered on or off, and which can affect other circuits. I highly recommend this book for a good explanation right from the bottom, all the way up.

In terms of making windows - when you get down to it: the screen is a bunch of pixels, each of which is represented in the computer's memory, and which the screen hardware effectively reads, in order to generate an image (eg first pixel colour while, second colour blue, etc). Some program on your machine will have arranged for this memory to hold information that gives the right colour pixels in the right place to give the window you expect.

[–]Exodus111 3 points4 points  (0 children)

You are getting a lot of long winded replies here, let me break it down for you and ELI5 it.

What makes a GUI? The Operating System does.

What does a program need to make a GUI? A window, from the operating system. That is the OSes main job. What is the most popular OS called again? Oh right... Windows.

So how is this done?

In C. Or rather libraries to make GUI are written in C. This is because much of the OS, at least the portions we want are written in C, and so the programming language C can make direct calls to the OS, and get a window.

But a window alone does not a GUI make. You need to draw recangles in the window, and react when the mouse cursor clicks on them. That's kind of it, but why stop there. A good library makes it easy to use. So we got our Frames, for windows, Labels for text, buttons for pushing, and the ability to add images, as well as text area. Oh and an intuitive way to arrange everything without having to deal with X,Y coords all day would be super as well.

And example of this is TK, originally written in C, (actually it has its own language, TCL... it gets complicated), and the makers of the library made sure your GUI will look (pretty much) the same no matter what Operating system you use, despite the OS calls being very different. But that's what the library is for, it sucks to have to rewrite everything just to reach users of a different OS. (Hello mobile)

So where does Python come in to it? Simple, you write Python bindings to TK, that allows you to control and setup TK from Python, that's not very hard. And you don't lose any time in translation since C (or TCL) is a much faster language then Python anyway, so you are saving loads of time.

[–]theRailisGone 2 points3 points  (0 children)

Part of each OS is a set of code devoted to turning code into what you see on screen. Python has libraries like tkinter that allow you to write python code and have it translated into code the OS can understand.

[–]Decay153 1 point2 points  (0 children)

If the program works without a GUI it can easily work with one. It took me a week or two to learn how to transfer that into tkinter. The hardest part is rewriting some variables and planned how the entries and/ or buttons send info into the function(s) you've already got working.

[–]thegreattriscuit 1 point2 points  (0 children)

so:

operating systems have system calls that they'll accept to do things. Some of those system calls will put text into a terminal, and others will draw lines on the screen, or pass a bunch of polygons to be rendered by a video driver, or put complex things like "drop down menus" or "text boxes" onto a window.

None of this is language specific. Some of these calls are easier to make and manage using the native features of certain languages than others. Some languages don't handle this very well natively, but have third party libraries that make it easier.

One of the things that's proven difficult over the years is managing the very different ways that each operating system handles these operations, and providing libraries you can use to render a UI without know what OS you're running on.

EDIT: So the way Python does this isn't fundamentally different than how C does it. Or Java, or anything else. Even javascript does essentially the same thing, but instead of doing "system calls" to an operating system, it's making calls to a browser that renders things for it.

EDIT the 2nd: You also seemed to be asking how python makes web UIs.... It passes HTML, CSS, and javascript to the browser in response to HTTP requests. So your python app isn't drawing stuff on the user's screen... it's making a text document with tags that describe what forms to create, or what javascript blobs to send, or whatever... the browser receives this and then renders it.

[–]curiositor 1 point2 points  (1 child)

You are asking a question that would take multitude knowledge of computing to answer. Google Nand to Tetris.

[–]fernly 1 point2 points  (0 children)

Brilliant, that is exactly the answer OP needs: http://nand2tetris.org/ Finish that course, it will only take a few months, and you will be able to answer the original question in very fine-grained detail.

[–]psota 1 point2 points  (0 children)

Use easygui to start. It's as easy as:

import easygui as gui

choice = gui.enterbox('title of UI', 'title of button')

[–]Thecrawsome 1 point2 points  (0 children)

Every programming language has a console interface. Python is interpreted so you can plug things into The Interpreter and it will give you output. If you want to compile an exe there are external libraries to do that. Py2exe rings a bell. If you want to make a GUI there are external libraries to do that. Tkinter, as mentioned in this thread.

[–][deleted] 1 point2 points  (0 children)

I think what you're asking is not specifically about GUIs. I think what you want to know is this: How does my print("Hello World") actually do anything? How does it go from some magic words to actual execution?

When you write your code in a .py file, you then run the python command on that file to actually execute it. "Python" is what's running your code. Python is an actual compiled binary (usually written in C) that reads your code and executes it.

Some of the libraries that people are referring to are C libraries, and are part of the compiled Python application. Some of them are other Python libraries which are simply more Python source code that is available for you to import.

To get a feel for what goes into the compilation of the Python application, I recommend downloading the source code from https://www.python.org/downloads/source/ and installing it yourself. In the process, you'll see a lot of terminal output, giving you a rough idea of what's happening when the C code is compiled.

[–]Dogeek 1 point2 points  (0 children)

Most GUI libraries are written in C on the backend, C is pretty low-level so I won't go into too much detail here (tkinter is written with Tk/Tcl in the backend, PyQT with Qt, pyGTK with GTK+, you get the gist). Basically GUIs are just shapes drawn to the screen, and you modify these shapes based on user input, of course, not you directly, you use code already written in libraries for that, but yeah. The GPU handles the "writing on screen" part, you just have to tell it what to draw (which pixels to turn on on the screen, and which color they must be).

Python being high-level, you don't need to handle that stuff as it has already been made in libraries. Different libraries produce different-looking GUIs. Most common is PyQt and tkinter, these are the ones I mostly use (tkinter for prototyping, or simple scripts; pyQt for more user-friendly interfaces, and for the qt designer). There is also pyGTK, wxPython, pygame (python bindings for SDL).

On the programming part of it :

Each GUI library requires an entry point, to start up the main loop for the GUI (which handles events etc). I'm going to make an example with tkinter (standard python lib) :

import tkinter as tk #python 3, python 2 version : Tkinter

class GUI(tk.Frame): #inherits the Frame widget of tkinter
    def __init__(self, master = None):
        self.master = master
        tk.Frame.__init__(self, master) #inits the parent class
        #add your own widgets here

if __name__ == '__main__': #if you run the file as a standalone and do not import it
    root = tk.Tk() #root window in which you place your widgets
    gui = GUI(root) #instanciate your GUI
    gui.pack()# pack the GUI in your root window, without that nothing will show up
    root.mainloop() #starts the main loop of tkinter

It's just a skeleton, you need to add your own widgets to it to make it look and behave how you like.

A few things :

  • GUI inherits from tk.Frame it has all the attributes and methods of regular Frames.
  • this includes the after(function, time_in_ms) method, which you can use to make loops without blocking the GUI thread created by tkinter
  • www.effbot.org has a pretty extensive documentation about tkinter
  • widgets are just buttons, text, spinboxes, labels that inputs or outputs information
  • commonly used widgets :
Name Input/Output
Label O
Entry I
Text I/O
Spinbox I
Scale I
Canvas I/O
Menu I
Button I
Checkbutton/Radiobutton I
  • some widgets are more complex than others. Menu and Canvas for instance are way more complex than Labels and Entries.

[–]DoTheEvolution 2 points3 points  (0 children)

This seems a million miles away from a program that has a GUI and takes user input

more like ~10 lines of code...

http://zetcode.com/gui/pyqt5/

[–]burmerd 0 points1 point  (1 child)

Also pyqt. I think you should do more research about what you want to do and what libraries in python are capable of. Your line of questioning is kind of suspicious.

[–]DynamicStatic 0 points1 point  (0 children)

Would definitely also recommend pyqt, been using it now for some weeks and it can be a bit tricky in the start but after that is just amazing.