Beginner Showcase
tkinter was shockingly easy to write a small overlay GUI
I did a project mostly over the weekend to write a super simple small overlay for an online game. I wanted it just to include some updating text that displays the ping times to the server: https://github.com/notatallshaw/fall_guys_ping_estimate
Edit: The screen shot is in the above link, it's nothing special, it's some updating green text with a black background that sits on top of any application (you can't even move it yet).
I was assuming to make an overlay feature I would need to use PyQt or wxWidgets. But it was actually just a few lines of tkinter to get working.
Despite having never done any non-web GUI programming I had a simple version up and running in less than an hour. I definitely think I might make more quick tools with a GUI in the future.
Yeah, which was fine for this project as I'm overlaying a game and games never try and look native.
I might try and make it look like the game UI at some point, but I feel like I would be stealing from this project which already did that: https://github.com/ShootMe/FallGuysStats (if you scroll down to the "overlay" screenshot).
Correction: “stealing” code is fine as long as you comply with the license. Some licenses like GPL require more than just credit. Sometimes there isn’t a license which means you can’t use it even if you have the code (eg leaked windows source code).
The code in question from OP is MIT which is basically do whatever you want it.
Yeah, also FYI I meant stealing the concept, not the code or assets.
The whole point of this was to be a bit of fun and learn new things, which I did, I learnt a lot more about tkinter, pyinstaller, and github workflows. I was particularly happy I could get the executable build to work entirely on the github workflow side.
But can it be compiled to a decently sized exe? (5 MB or so for what OP has made) or are we stuck with the py file?
Edit - https://youtu.be/QWqxRchawZY?t=5m53s yeah approx 7 MB for a very simple program. That's huge tbh. But hopefully it doesn't bloat too much if you restrict your libraries usage.
I find it frustrating that he didn't find the "--noconsole" option, I feel like it's in most of the getting started examples and took me less time to find it than watch him not find it.
It is a large exe to run a small box, but if you think it's basically everything you need to run Python + Your script files, it basically doesn't matter how much code you write (as long as you not add big dependencies), the exe is going to stay around the same size.
Yeah, it's not as compact as would be ideal, but it's understandable, given that you're basically shipping an interpreter, a GUI library, and your app, whereas a hello world compiled to native code and using native UI just needs the (very compact) machine code for the app itself. (Plus a small runtime in most cases, but that's negligible.) Reading the Tkinter Wikipedia page, it looks like a Tkinter app might also include Tcl itself?
I'd be curious to know how slim a tiny C++ app with ImGUI could be, since that is a library with a similar set of widgets I'd use for similar purposes (game overlays, dev tools, one-off utilities), but, being C++, it'd be compiled.
A simple Tcl/tk would also be interesting, although I don't know if Tcl has compile to EXE tools like Python.
FYI I gave it a go and with the options standalone, onefile, zstandard compression, enable-plugin=anti-bloat, noinclude-pytest-mode=nofollow, and noinclude-setuptools-mode=nofollow enabled it ended up being only 8% smaller than the pyinstaller file.
Not worth it for me given it makes it harder to debug and compile, and no potential performance benefits would be that useful for me, but an interesting tool I'll keep in mind in the future.
PyQt makes really professional-looking applications, although the learning curve is steeper than Tkinter.
You also need to read the dual licensing that PyQt uses as it is kind of confusing. There is PySide / Qt for Python that has a somewhat looser license though.
Kivy is made primarily for mobile, although it works on desktop. It makes no attempt to look native at all though. I feel like it is one of the hardest ones to learn because it mixes in the Kv language, which is kind of like CSS for Kivy.
So about a year and a half ago I was given a web project, and I started coding it in Dash, it's like a Python backend that writes the HTML and JavaScript for you.
It was real delight to see users directly interact with my code.
TK is super easy to work with. The layout engine is probably the most straightforward of any I can think of--you tell it where you want things, how to size them when the container resizes, and that's that.
One thing that really saddens me is just how many people just parrot how 'Tkinter sucks' or something to that effect, when they don't even know how powerful Tkinter is.
Quite to the contrary: Tkinter is brilliant. You can get amazing UIs done if you know how to work Tkinter well, and you can get them done really fast without any other dependency since it's in the standard library.
Yeah, being in the standard library was a big plus for me because I also wanted to make my project in to an executable so others can try it without needing to know about what Python even is.
I'd only used tools like PyInstaller and cx_Freeze as quick PoCs in the past but I remembered the more external dependencies you have the more complex it gets.
Programming in general is rife with cargo cult mentality. I've been a C developer my entire career and have to occasionally deal with newcomers who take issue with the odd goto with zero justification because they're parroting "goto bad" which is based on a misinterpreting of a paper from over 50 years ago.
I will admit there is nothing objectively wrong with goto, but I'm perfectly happy to join that cargo cult. Considering the wealth of options in control flow that (to me, yes it's subjective) seem much clearer, it just doesn't seem worth it.
While I do agree that goto hasn't been treated fairly by history, I also think it's nice having some "rules" that aren't rules. Following unenforced standards makes it easier to read other people's code. You can still break them when it's either necessary or will save a ton of time, but it's better to refrain when possible.
There are common patterns in C like resource cleanup on failure where goto is the cleanest way to handle it, but I've seen some pretty gnarly and buggy patterns for the sake of just not using goto.
To be honest when I hear someone say they just categorically won't use goto I consider it a sign of a bad programmer.
Well, I categorically won't because it means I'm C and I shouldn't be doing that :)
I completely recognize that it's probably being done under the hood, but I'm pretty happy that it's not a part of "modern" languages (of course C is still modern in the sense that it's used a lot). While I enjoy figuring little things out in C, I'm pretty happy that Python and Java exist.
sadly PySimpleGUI is quite limited. i have been using PySide6 for a overlay app im making and found it surprisingly easy to work with, contrary to some foggy memory of QT being quite annoying
Apologies, I expected like 10-20 up-votes and a few comments. This got way more attention than I wanted. I'll try and de-clickbait any titles in the future unless I mean to garner so much attention.
Is there a good way to embed images in a text post? As it was like one of the first things on the github description it seemed redundant posting a link to imgur or something.
I don't think so (so not your fault), it just might be worth mentioning where to find a screenshot in the post. Some people (lazy ones, like me) won't bother clicking on the link until enough interest is piqued.
For anyone else posting, here are a few things that are frequently requested on any programming post: a screenshot, source code, video/demo.
I was originally going to post this as an image post or a link to a screenshot but then I read the rules that showcases have to be text posts.
All in all this got way too much attention, it's a really simple fairly dumb app. I was just particularly happy with how quick I was able to put it together and wanted to show it off to a few Python developers.
Thanks for the post, I have half-heartedly tried several of the Python GUI options, but not with any real purpose, so I never really finished them (I also probably wasn't starting with a simple GUI but something more elaborate). You have given me a push to try again. 👍
Yeah because I'm a self taught coder I like to start my projects with very little structure and just see where things go. If I find out my approach is bad that's fine, I've learnt something new and I'll just take an entirely different approach.
Tests seem to encourage the opposite of this, but then I also have never really had to work with others on the same project as I'm usually the one Python developer in my team.
You're thinking of TDD, which is often conflated together with tests in general, but I'd rather have tests written after the fact or as it gets cleaned up and refactored, than no tests at all.
I often write like a handful of high level, integration-like tests to set my public API, then write unit tests as I code. I don't do strict TDD at all. You certainly run your code to check if it does the thing you think it does, right? You make a change, then run it again? Then you're already doing the tests you should be writing, you're just doing them manually instead of "as code". Tests are just a way to automate exactly this, and make those tests repeatable in the future, either by yourself or by another developer.
I've been in your position, tests can seem pretty complicated, but they're not. A couple of hours playing with them and you should be good to go and test all the things.
You make a change, then run it again? Then you're already doing the tests you should be writing, you're just doing them manually instead of "as code".
I like that way of thinking about it, I wasn't thinking of TDD but I was thinking that tests force you in to sticking with a particular approach once you start.
But I like how you phrased it here, I'll endeavor to try and write some tests instead of rerunning my code next time I do a project.
To be fair if I'm writing one-off scripts or small projects for fun, I may skip the tests part. But if it's something I have to maintain, 0 possibility that I'll skip them.
My current project at work is not easy to run locally due to many external dependencies and moving parts, so by writing tests I can work for days before needing to run my changes on the shared dev environment (unfortunate result of our current infra). I just did a major refactor of a whole swath of legacy code that had 0 impact on the functionality cause I had tests telling me the output format didn't change and everything kept returning the right stuff. 100% made my job easier.
It's a good skill to develop. At some point you get into the habit of writing testable code as you know what it looks like, too, so in my case it had a noticeable impact on the quality and maintainability of what I write. I just try not to get too anal about it where it doesn't matter very much.
Sorry, I wrote a comment before and deleted it. I totally forgot there was a reason why I was doing this.
The lambda is capturing and discarding the event arguement. If you simply do sys.exit then you are passing this event object to the sys.exit which I don't think it would expect. I tried it now and it means the final exit of the program prints: <ButtonPress event state=Mod1 num=1 x=12 y=12>
I think another other than a return of 0 is typically treated as an error code so this probably isn't great.
The problem with Thinker is that it does not look nice. Nowadays everyone in business want it to be nice - sometimes people stare at your app for 8 hours a day.
By complex I am talking about a table and a few labels that update, and a bunch of buttons. For this kind of thing tkinter works fine for me and everything is nice and snappy. When I add a non-default theme, it gets super slow. This is all I was trying to warn about.
Thanks for the suggestion, you basically have alternatives for all the OSs, if you want your app to appear "native". Again, surprisingly easy to integrate.
M-yeah, a lot of them look native, I'm sure some people don't like those themes, but if some desktops are using them, some apps need to look like they belong there.
Thanks! Python is my day job, but I'm doing a few things here I'm not used to: A GUI, making an executable, using GitHub workflows, publishing my code publicly!
It's a little trickier to set up, but I strongly recommend imgui+pyglet instead of tkinter. It's just a lot easier to write small little personal apps in it.
so the overlays is over a browser window? if you move the window, does the overlay move with the window as well? is it cross-platform?
Currently the overlay is in a fixed position 5 pixels down and 5 pixel right of the top left corner of the screen. It will stay there above all other Windows (browser, game, etc.).
I'm not using any platform specific code so the overlay itself should be cross platform. But I have not run the code on a different platform and the log scanner assumes you are on windows and attempts to look up the directory %USERPROFILE%. If someone plays Fall Guys on a non-Windows platform I'd be happy to update it.
I do want to make the Window dragable, there are some examples doing this with tkinter, but the code looks to be about the same length as my whole project so far so I've not messed about with it yet.
Here, I've extracted overlay.py in to a single working example. The important "overlay" part is the lines directly under the comment # Define Window Geometry
Hope this helps you:
# Standard Library
import sys
import tkinter as tk
from typing import Callable
from datetime import datetime
class Overlay:
"""
Creates an overlay window using tkinter
Uses the "-topmost" property to always stay on top of other Windows
"""
def __init__(self,
get_new_text_callback: Callable[[], str],
update_frequency_ms: int = 5_000):
self.get_new_text_callback = get_new_text_callback
self.update_frequency_ms = update_frequency_ms
self.root = tk.Tk()
# Set up Close Label
self.close_label = tk.Label(
self.root,
text=' X |',
font=('Consolas', '14'),
fg='green3',
bg='grey19'
)
self.close_label.bind("<Button-1>", lambda _: sys.exit())
self.close_label.grid(row=0, column=0)
# Set up Updating Text Label
self.updating_text = tk.StringVar()
self.updating_text_level = tk.Label(
self.root,
textvariable=self.updating_text,
font=('Consolas', '14'),
fg='green3',
bg='grey19'
)
self.updating_text_level.grid(row=0, column=1)
# Define Window Geometery
self.root.overrideredirect(True)
self.root.geometry("+5+5")
self.root.lift()
self.root.wm_attributes("-topmost", True)
def update_label(self) -> None:
self.updating_text.set(self.get_new_text_callback())
self.root.after(self.update_frequency_ms, self.update_label)
def run(self) -> None:
self.root.after(0, self.update_label)
self.root.mainloop()
def example_callback():
return str(datetime.now())
def main():
overlay = Overlay(example_callback, 16)
overlay.run()
if __name__ == '__main__':
main()
Well the code has grown a little since I posted it, but the core part is still very simple.
Tkinter runs an event loop, you have to tell it when you want to run the next method. I'm on mobile right now but there's a few other comments I posted here that explains it a little. But if it still doesn't make sense I'm happy to post a longer explanation next time I get to a computer.
87
u/driscollis Jul 22 '21
Tkinter is cool. It doesn't look very native but it's quite powerful