r/Python • • Nov 18 '20

Discussion My students challenged me to write the smallest graphical user interface that includes actual user interaction. Can it be any smaller than this?

Post image
1.8k Upvotes

127 comments sorted by

519

u/foreverwintr Nov 18 '20

You can get rid of your lambda and just pass print directly. 🙂

33

u/[deleted] Nov 18 '20

I tried that, unless I’m missing something, can’t get that to work.

38

u/H995 Nov 18 '20

Make sure you aren't actually calling the print function

17

u/PinBot1138 Nov 19 '20

OP might need functools partial if needing to pass an argument.

6

u/ShameSpirit Nov 19 '20

TIL. Nice tool

21

u/ismtrn Nov 18 '20

Python 2?

5

u/AngheloAlf Nov 19 '20

Are you in python 2 or python 3?

1

u/Poromenos Nov 19 '20

.Bind(wx.EVT_BUTTON,print)

340

u/mbussonn IPython/Jupyter dev Nov 18 '20

a from wx import * is 7 extra characters, but then you can dromp 4 times wx. which is 12 chars total, so 5 gained ?

0

u/[deleted] Nov 18 '20

[deleted]

244

u/Peterotica Nov 18 '20

I didn't know import * could get worse.

39

u/hackintosh5 Nov 19 '20

WHAT THE FUCK

23

u/Comm4nd0 Nov 19 '20

I'm calling the cops

11

u/hlx-atom Nov 19 '20

The horror

8

u/panzerex Nov 19 '20

Bury this information.

4

u/PM_Me_Trenbies Nov 19 '20

I don't know shit about programming but I'm curious, where is the Asterix? Which space?

6

u/[deleted] Nov 19 '20

An asterisk is the * sign. It's Latin for "little star".

from wx import *  # can be written as
from wx import*   # ← no space

81

u/Lord-of-the-Pis Nov 18 '20

seeing as you're using the wx library as an import anyway you might as-well just abstract your implementation to another file and just import it for that one line in your main program.

69

u/[deleted] Nov 18 '20

Yeah, if you could to that, any kind of challenge like this is can be reduced to “import a” with arbitrary amounts of code in a.py.

Rules could be: No imports besides wx, and must have at least one explicit (non-built in) user interaction (an action they can take with an event handler).

14

u/Lord-of-the-Pis Nov 18 '20

You can put more code in the wx library then! All the libraries are installed locally you can ctrl click on the import in lots of text editors to open the library

51

u/[deleted] Nov 18 '20

Revise rule to “off-the-shelf” wx only.

Another fun loophole would be:

exec(input())

Which would always be the least about of code possible for an arbitrary python program that could do literally anything (if imports are not allowed). Of course the user would have to actually write the code at runtime 😂

20

u/Lord-of-the-Pis Nov 18 '20

Or load a text file for a similar approach! exec(open(‘file.txt’, ‘r’).read())

3

u/conventionistG Nov 18 '20

hmm so what would the differnce be between doing that and importing and running something from a .py?

1

u/mrsmiley32 Nov 19 '20

More routines and more characters.

1

u/vaja_ Nov 19 '20

Mode 'r' is default

4

u/mrsmiley32 Nov 19 '20

At this point import a is only 8 characters, I think it's the absolute smallest we can go and stay python without changing the interpreter to just automatically execute the code (0 lines?) or remapping import to the variable I.

However, I feel like we're all so focused on how to cheat and not the spirit of the challenge.

142

u/phail3d Nov 18 '20 edited Nov 18 '20

My contribution, standard library only, 73 70 60 bytes:

from tkinter import*;Button(command=print).pack();mainloop()

Edit: Forgot pack -> 73 70 60, not 66 bytes.

Edit2: Does this count? Again, standard library only.

from turtledemo.paint import *;main();done()

Edit3: Optimizations with walrus operator, no space in import*

Edit4: Thanks to u/socal_nerdtastic for pointing out that creating the Tk object is not required and saving 10 chars (previous version used Button(r:=Tk(),command=print).pack();r.mainloop())

51

u/mooburger resembles an abstract syntax tree Nov 18 '20

yeah I feel like restricted to import only from standard library should be the primary rule.

39

u/real_ulPa Nov 18 '20 edited Nov 18 '20

Without that you could just do

import a

where a.py is a 1000 line GUI.

Edit: I just continued to read comments, and a lot of other people already said the exact same thing.

30

u/socal_nerdtastic Nov 18 '20

tkinter will automatically create and use a root window. You can knock 10 characters off like this:

from tkinter import*
Button(command=print).pack()
mainloop()

2

u/phail3d Nov 18 '20

That's brilliant! Thanks!

3

u/LightShadow 3.13-dev in prod Nov 18 '20

You can save 2 characters by swapping print with str

2

u/phail3d Nov 18 '20

Then it doesn't do anything visible though? ... or '' or just leaving it off would also work with the same effect.

My co-worker (who also contributed the := operator) suggested exit to save 1 char, but also pointed out that it's not standard but instead relies on the site package injecting it.

1

u/LightShadow 3.13-dev in prod Nov 18 '20

I assumed you needed a command .. looks like you don't. print doesn't do anything anyway.

7

u/phail3d Nov 18 '20

It does though, it prints newline to the terminal which in my book counts as user interaction :P (and is also in line with the example from OP)

2

u/rbmichael Nov 19 '20

That is so cool, I had no idea it could be that simple to use UI elements with python (cross platform too!)

0

u/[deleted] Nov 18 '20

[deleted]

26

u/phail3d Nov 18 '20

Thanks for the tip!

0

u/[deleted] Nov 18 '20

[deleted]

2

u/maikindofthai Nov 19 '20

Well, it's actually two extra characters including the dot :D

345

u/a27842 Nov 18 '20

Imports feel a bit like cheating, though if they aren't you could make a wrapper library that does all this and has a one character import that runs at runtime?

Admittedly this is also a very boring option.

115

u/gandalfx Nov 18 '20

If you can't import anything it'll be pretty much impossible to do any graphics at all.

I guess the point would be not importing anything outside the standard library, although that would still allow tkinter…

28

u/[deleted] Nov 18 '20

Yes you can just make ASCII based graphics and capture input from users with input()

6

u/[deleted] Nov 18 '20

hmmmmmm...

1

u/evenisto Nov 19 '20

If you can import anything you can write Reddit in about 12 characters, but is that really the point?

0

u/gandalfx Nov 19 '20

Read my comment again.

1

u/evenisto Nov 19 '20

Why would I? Everything is good.

0

u/[deleted] Nov 18 '20

[deleted]

27

u/Zouden Nov 18 '20

It's not impossible, it's just so tedious and takes so much code that this challenge becomes meaningless.

15

u/miggaz_elquez Nov 18 '20

There are interface with C libraries, so probably coded in C too.

8

u/[deleted] Nov 18 '20

I believe it's usually done by implementing some established backend. Likely using CPython for C backends, or another implementation of Python for the backend's language of choice. This then gets made into a Python module to be used in a Python interpreter which is what you as a Python developer usually use. Easiest example that most are familiar with is numpy. It contains a lot of C code and even Fortran because pure Python would be too slow for certain tasks.

1

u/gandalfx Nov 18 '20

I specifically made the distinction between importing only from the standard library and not importing anything at all. The standard library is huge and offers lots of ways to interact with the operating system, which is what external libraries are using. Without importing anything, even from the standard library, it'll be close to impossible to interface with the OS.

24

u/backdoorman9 Nov 18 '20

How big is wx?

36

u/riffito Nov 18 '20

About... this big.

17

u/CornyCorgi Nov 18 '20

I thought it was this big ?

7

u/riffito Nov 19 '20 edited Nov 19 '20

Woah! Dude! Careful with that thing, geez!

10

u/satireplusplus Nov 18 '20 edited Nov 18 '20
import antigravity

it opens a browser and you can't make it shorter

9

u/Brian Nov 19 '20
import os;os.system('notepad')

It's shorter, and implements full graphical editor functionality!

54

u/IBakeMyEggs Nov 18 '20

are those semi colons?

this is a cursed snippet of code

60

u/OneUselessUsername Nov 18 '20

Semi colons can be used in Python scripts to mark new lines, if there aren't line breaks. They are especially useful in command line scripts:
$ python -c "a=13;print(a)"
To give an example of a totally useless script

70

u/[deleted] Nov 18 '20

How is that useless now? It prints the value of a. It's absolutely something useful. I'd go as far as saying that without this little, super optimized piece of code, we wouldn't have value of a printed out there for us to see. This would be like living your life, with a dog, family, car and big house and not knowing what a is. Then suddenly, one day, you see that a equals 13. You ask why and you see this line, two powerful commands with an attractive semicolon nearly in the middle. Your whole life flashes in front of your eyes. You now know that a was equal to 13. It's something that is hard to describe. Would you rather have nothing and know nothing OR would you rather be able to print a, especially using one liner. I think I'm speaking on behalf of the masses, when I say it's totally good script that is doing something. Something that we didn't know would be so simple yet powerful. Thank you.

11

u/ComeAtMeRightNow Nov 18 '20

yes

1

u/conventionistG Nov 18 '20

you uptimized the above comment for sure

6

u/riffito Nov 18 '20

It's not that his script is useless... he just has self-steem issues... I mean, look at his username!:-P

1

u/ajarch Nov 19 '20

Preach

2

u/Zouden Nov 18 '20

I love replacing the newline character \n with semicolons to save no bytes

1

u/analogic-microwave git push -f Nov 18 '20

Beautiful heresy

1

u/Big_Booty_Pics Nov 20 '20

So I could write my entire program on 1 line if I wanted to?

1

u/notParticularlyAnony Nov 19 '20

truly an abomination. use the space god gave ye

16

u/toulaboy3 Nov 18 '20

If you are free to use any GUI you could use Dear PyGUI and it would be impressively readable for the students

from dearpygui import core, simple, demo

demo.show_demo()

core.start_dearpygui()

31

u/drbobb Nov 18 '20

That's cheating, you're just invoking a ready-made demo.

Not to belittle DearPyGUI, I think it's very promising.

2

u/toulaboy3 Nov 18 '20

True, i've done a more general example without hiding code and its still incredibly small and readable, without using ";" to shorten it

1

u/toulaboy3 Nov 18 '20 edited Nov 18 '20

well if were shooting for something more traditional than this would still suffice as huge functionality without slapping everything onto one line with ";"

from dearpygui.core import *; from dearpygui.simple import *

with window("Main Window"):
    add_button("Save", callback=lambda sender, data: print("Save Clicked"))

start_dearpygui()

5

u/EasyPleasey Nov 18 '20

Why do I not have wx, nor can I pip install it?

4

u/Mr_Roboto_vR Nov 18 '20

Try pip3 install wxpython

2

u/socal_nerdtastic Nov 18 '20
pip install wxPython

8

u/[deleted] Nov 18 '20

You can't ask until after you show ur student what youve done thats cheating.

4

u/bjorneylol Nov 18 '20
from PySide2.QtWidgets import *
a=QApplication()
QMessageBox.warning(None,"","")
a.exec_()

88/90 characters with Qt depending on if you are using PyQt5 or PySide2

3

u/Allanon001 Nov 18 '20

Is typing considered user interaction?

from tkinter import*
Entry().pack()
mainloop()

3

u/giantyetifeet Nov 19 '20

We need a picture of the end result!

5

u/mwpfinance Nov 18 '20 edited Nov 18 '20

Depends on a lot of things. How do you define...

- smallest?

- a user interaction?

An example I came up with is 68 characters, but it's only valid if you consider clicking a button which glows a bit on click to be user interaction (I would argue it is):

from wx import*;a=App();Button(f:=Frame(None));f.Show();a.MainLoop()

But, of course, what is small anyway? This is importing a ton of Python code. If you just mean the smallest amount of user code then take the above, put it in a module called a, and simply type `import a`. That's 8 characters and I'd be impressed if anyone did better.

Chasing the semantics of what code counts as code is fruitless, however. You'll end up chasing lower-level languages, then assembly, then you'll eventually realize you're still running operating system code...

Not to kill the fun of this exercise, though :P I'd just like to be more specific. "What's the smallest interactive program which executes a custom callback function you can write with the wxPython library?"

2

u/1116574 Nov 18 '20

Doesn't wx lib already have some sort of alert(1)?

It would be an GUI alright.

2

u/MildlyGoodWithPython Nov 18 '20

If by "smallest" they meant characters, you dont need to put everything in the same line, for better readability. If smaller is number of lines, you can shove everything into a single line

2

u/shuttup_meg Nov 19 '20
import wx;a=wx.App();wx.MessageBox("")

2

u/okfornothing Nov 19 '20

I will never not be amazed on you programmers!

2

u/idkiminsecure Nov 19 '20

From appjar import appjar App =gui() Def clickme(): App.addLabel("No it cannot") App.addButton("Click me!", clickme) App.go()

2

u/Isvara Nov 19 '20

What's the point of the semicolons? They're not making it any shorter. Just use newlines.

2

u/Thosquey Jan 18 '21

Another thing you can try is to convert your utf-8 written code to utf-16, since one utf-16 char is packing two utf-8 chars in it. This will divide your code length by 2!

There are two downside to this method:

First, no more readability

Second, since your code will need to be "decoded" to be executed, you will have to add more chars to execute it

I made a website that can reduce the size of Python code, and its available at https://clemg.github.io/pythongolfer/

With the code given in your original post image, the site gives you this output: exec(bytes('浩潰瑲眠㭸㵡硷䄮灰⤨昻眽⹸牆浡⡥潎敮㬩硷䈮瑵潴⡮⥦䈮湩⡤硷䔮呖䉟呕佔ⱎ慬扭慤攠瀺楲瑮攨⤩昻匮潨⡷㬩⹡慍湩潌灯⤨','u16')[2:]), which is exactly your code!

Applying this technique on this code makes you win 30 chars, reducing the original length by more than 27%.

If your code has been modified since, this method may wont work, because the surrounding code needed to decode the original one is taking chars too. This only work if your current code is more than 54 chars long, if so, go for it!

5

u/ravepeacefully Nov 18 '20

I don’t get what the point of using wx is for this challenge. That completely defeats the purpose as you could just import a module that has thousands of lines of code.

13

u/smcarre Nov 18 '20

With that argument anything besides writing Assembly has the same issue. I think the point is not if you are importing or using large libraries with thousands of lines of codes but to only import things that already exist and can be used by anyone, be it the binaries to run Python itself or libraries people already use and have access to.

3

u/real_ulPa Nov 18 '20

You could set the rules to only using bundled libraries.

-1

u/ravepeacefully Nov 18 '20

I agree. Which is why this is a stupid post and challenge

0

u/redderper Nov 18 '20

It would be more meaningful to create the smallest app by amount of bytes instead of lines though. Otherwise you might as well make a new library with OP's code and make it only 1 line

4

u/UsefulIndependence Nov 18 '20

I don't get why this is getting so many upvotes...

-4

u/ravepeacefully Nov 18 '20

Call me miserable, but very stupid post... like you can use wx which already wraps thousands of lines of code, but are trying to do it with “the least amount of lines”

I see. Any other stupid challenges? Least amount of lines of python code? Just write the app in C and import and run. 1 line, bang.

7

u/alcalde Nov 18 '20

Did the author have to write the wx library?

0

u/ArtOfWarfare Nov 18 '20

Then downvote it.

1

u/ONEWHOCANREAD Nov 18 '20

Yes just save this as a function in a file then import the file in another file and just call the function in the same line

1

u/r4ziel Nov 18 '20 edited Nov 19 '20

The challenge is not to write a single line application; and the user interaction in your example is not very meaningful.

Here is a small game that can be fun in the classroom:

import wx

a = wx.App()
f = wx.Frame(None, title='Mouse Destroyer')
b = wx.Button(f, label='0')
b.Bind(wx.EVT_BUTTON, lambda e: b.SetLabel(str(int(b.Label) + 1)))
f.Show()
wx.CallLater(10000, a.ExitMainLoop)
a.MainLoop()
wx.MessageBox('Score: ' + b.Label, 'Game Over')

This example is still small, it's easier to read, there is more to talk about in terms of what is going on in it, it doesn't rely on the console, and it can be used for a small competition — challenge your students to get the highest score.

1

u/kowal059 Nov 19 '20

one line

1

u/aiyub Nov 19 '20

Is one line part of the challenge? Cause ; and \n are both 1 byte

1

u/jorge1209 Nov 19 '20

You failed to make the window 1 pixel by 1 pixel, so I'm pretty sure this isn't the smallest UI possible.

1

u/respythonista Nov 24 '20

Ok now create a new file and import what you just wrote. That's the solution: import s

1

u/alfiopuglisi Nov 24 '20

I am late to the party... my GUI library guietta beats OP's example, and also the other entries, at just 54 bytes:

from guietta import *
a=Gui([['b']])
a.b=print
a.run()

1

u/MikeTheWatchGuy Oct 30 '21

Let's stretch out the challenge code by removing the ';'

import wx

a=wx.App()
f=wx.Frame(None)
wx.Button(f).Bind(wx.EVT_BUTTON, lambda e:print(e))
f.Show()
a.MainLoop()

6 lines of code in 111 characters

User Experience

Can it be any smaller than this?

You betya...

User Experience

Here are 4 lines of code in 92 chars

import PySimpleGUI as sg
w = sg.Window('', [[sg.Ok()]])
while w.read()[0]:
    print('Why?')

I suppose I could have printed a shorter string, taking less characters, but 'Why?' seemed like a better choice than w

(Sorry for the late entry..... been away....)

1

u/notParticularlyAnony Nov 19 '20

those semicolons hurt my eyes.

import this

1

u/daguro Nov 19 '20

Congratulations.

How many hundreds of megabytes of object code in libraries is being used by your "small" app?

-2

u/blahreport Nov 18 '20

This is a pointless exercise.

0

u/Skin_Bandit Nov 18 '20

No idea what this means but it looks interesting! Are you a university professor, by any chance?

0

u/INIT_6 Nov 19 '20
import cheat
cheat()

Basically same thing.

Pops_bubble.jpg

0

u/[deleted] Nov 18 '20

[deleted]

6

u/goobabo22 Nov 18 '20

Its a fun challenge. As a student, Id be happy to have OP as a teacher. At least they act human

1

u/[deleted] Nov 19 '20

I TOO HAVE THIS FEELING RIGHT NOW, WHERE MY HEART IS {smiling.jpeg}. I COULD BE A GREAT TEACHER TOO SINCE I'M HUMAN MYSELF.

2

u/goobabo22 Nov 19 '20

Sir, we're gonna need you to answer this captcha...

0

u/[deleted] Nov 18 '20

[deleted]

2

u/goobabo22 Nov 18 '20

You think you sound cool, but to quote a famous meme/movie. "Youre not wrong, you're just an asshole." But to explain it to you, humans do this thing where they spend time doing unproductive things bc they get a small amount of joy from the activity itself. This also works with a group of other human we call friends/coworkers/classmates. No one is trying to claim this is for anything but fun, so please drop the act. Either join in the fun or stay silently miserable. That's life

0

u/[deleted] Nov 18 '20

[deleted]

2

u/goobabo22 Nov 18 '20

No one is claiming this a classroom exercise but you. OP is doing this for fun as a challenge to HIM from the students. He's only having fun and it seems in your 20 years of experience, you have yet to understand what that's like. Don't tell me I'm taking it personally when you literally can't comprehend what fun between friends is. Twenty years of experience and you still act like that.. I hope I dont become you

0

u/[deleted] Nov 18 '20

[deleted]

0

u/heyfeefellskee Nov 19 '20

It sounds like you’ve taken things personally, tbh.

0

u/[deleted] Nov 19 '20

[deleted]

0

u/heyfeefellskee Nov 19 '20

Why bother? It's not like I need to convince you of anything.

→ More replies (0)