A Tkinter python multi-platform app/GUI

We wrote on python/wxpython Hello World a very simple window/gui. This time we are going to do it for real. The aim is to write “the app/GUI” that will run one command or another depending on the OS. We are going to use pure python, so that provided we have it installed (and we probably have it) our app will do the same. This time, instead of wxPython we are going to use Tkinter message boxes, for the simple reason that this seem to be more popular for doing what I want at the end. You can find a comparison on this activestate blog entry from 2015. I will cut to the chase for you:

wxPython: 6 seconds
tkinter: 1 second

Speed is important: nobody likes to wait for a window you don’t know if it’s going to pop up or not. Tkinter is also the default GUI toolkit for Python. So let’s do this. I’m going to write pieces of code, so this is going to be an ikea-type of post (build the app yourself). First we are going to discriminate by OS. How can we do that?

import sys
if sys.platform == "win32":
    print " Current OS: " + sys.platform 
    cmd = 'C:\Python27\python.exe --version'
elif sys.platform == "linux2":
    print " Current OS: " + sys.platform
    cmd = 'echo hello' 
    print "No support for the " + sys.platform + " OS"

Remember to indent your code. Python is very sensible with that. Depending on your editor, this will be more or less easier. To know how your OS is called, you can use the python command line.

>> import sys
>> print ” Current OS: ” + sys.platform

Next step is define the layout of our GUI. You can start with a working one, for example, here you have a simple hello world GUI. Now that you saw a Tkinter GUI, we can write one from scratch. On a GUI, the layout is very important. Also very annoying. So making a simple sketch of the app may help. Like here the title, here an entry field, here a check button, here start/stop button. We can change the look of the Tkinter buttons as we like to have the text is in blue or the background in yellow. It is important to know, anyway, what is a button, what is a Tkinter Entry, and so on. After a little fiddling with frames and grids, and with packing options, for my app I use the more natural absolute positioning. How all of this is coded?  In principle, we need a main loop.

#### MAIN LOOP ### 
if __name__ == '__main__':
          root = Tk()
          app = App(root)

This can go to the end of your file. Over it we need to define App. On App we have the buttons, entries, and functions linked with the buttons. That is, what your app does. A basic example is:

class App(object):
    def __init__(self,master):
    ### GUI elements
    self.clock = tk.Label(root, text='H:00 M:00 S:00')
    self.clock_button = 
           tk.Button(root, text='Start', fg="red", 
    self.source_label = tk.Label(root, 
           text='Get a Directory')
    self.source_button = tk.Button(root, text='...',
    self.source = tk.Entry(root,width=10)
    ### GUI positioning
    self.clock.place( x=210, y=10)
    self.clock_button.place( x=10, y=10)
    self.source_label.place( x=10, y=40)
    self.source.place( x=150, y=40)
    self.source_button.place(x=260, y=40)
    ### button functions
    def get_dir(self):
         source_dir = askdirectory(mustexist=True, 
                      title='Select Directory')
         self.source.delete(0, len(self.source.get()))
         self.source.insert(0, str('"{}"').
              format(source_dir.replace('/', '\\')))
         return source_dir

What was that? Our class App has 5 components (buttons. labels, entries). They are drawn at fixed positions using place. The command keyword points out to functions that we define later on, like get_dir.

Note that we don’t define startclock. This has a reason. Dealing with time and Tkinter is very tricky. There are hundreds of post about it. I will refer a few here. At the end I used a modified version of the stopwatch example from StackOverflow. I needed a timer also. For that, I used the after call. I tried with sleep, and stop, without reaching stability. So please learn how to use the after method. Otherwise, you’re doomed. Specially if you use infinite loops (while 1: or similar). Another concern was the stability of the GUI on long runs. You know, sometimes you need to refresh your Tkinter window or something similar. I did that using the method update_idletasks over my main loop:

#### MAIN LOOP ### 
root = Tk()
app = App(root)

I added that in addition to my after call on “App”. I used update_idletasks instead of update because update seems to have some issues. There is of course a StackOverflow post discussing that. But it is not clear for me which one is the most stable. My after call looks like this:

def run_timer(self):
   ### a lot of code here
   self.clock.after(timestep, self.run_timer)

What I try to show is that after is called with the same function it is as an argument.

On a happy ending,  another example: here you have a color changing window written on tkinter using after timer events. It’s doing nothing but it’s a nice one 😀


The water wedding (XXIII)

They started to be visible way before we reached them. The Towers, although mineral, were looking from afar like three giant shinny trees deployed of branches and leaves. I could appreciate now they are not of the same size, being the left one the biggest one and the central one the smallest, but they are equally enormous. Without nothing to compare them with, and since I don’t make any sense of giving their size in meters, I will say they were as tall as snowed mountains. About their thickness, I have a more human scale. They are thin. As thin as a couple of buildings sticked together. So marvellously thin. And covered in scales.

Around them, a lot of activity that I was not able to detect from “above”. I was not able to make back to my aerial eye, as I call it, despite Hakim asked me repeatedly about it, and now it’s too late. I leaned that the same way I can now feel Hakim close by, the Towers will feel that we are…enhanced, and keep all the vigilance systems on us unless we ignore the nanocites. Apparently, there are more people than us with nanocites in the Empire, some of them not even knowing what they are for. Inquiring about this point, I learned about the maintenance issue. You need a facility to activate them, and they need to be charged from time to time. How they are charged will depend on the model. So let’s say like this: they (who?) load you with inactive nanocites, then you don’t know they exist, and at one point they will be just like little floating metallic ships on your bloodstream, that’s it. There will be no way to activate them back in a non-invasive way (meaning without the host knowing about it) but they will still trigger the alarms in place here, for example.

Our situation is then a gamble. We think they either don’t know what the alarms mean, or they know what they mean but they don’t care. The Shadow Guard is an elite group, but they are not soldiers of the last War. They are, as far as I know, more humans than us at this moment. For example, they may fail on delicate tasks not having our nanobot supervision, and they may neglect the sensorial information if they don’t understand it. Luckily I can’t do that anymore, my nanos will, willingly or not, answer my questions if they can, or make me think about something I’m not able to evaluate as a real risk. Or I think they will. What makes us some kind of super warriors… but I’m digressing here.

– So which gate are you going to choose, my love? – Hakim told me the three towers make two gates, and that the one you choose is supposed to mark your destiny. Something about an old culture, blah blah blah. The “gates” are one kilometer wide, and they stand over a planitia, so there is no room for a mistake. You need to head one or the other, or you will look like you want to collide with the central one. That may not be a smart move if they are defended.

– Let’s choose the right one. It seems to be right, if I am allowed to use the joke. Of course what is right depends on your point of view! – He laughs. Our mood is great. I keep driving. We are around ten klicks away and approaching, all the magnificence of the structures clearly visible. What is not visible is any observation point. I decide to ask about it. – Are we supposed to stop when we cross it?

– I don’t know… I hope not. I want to finish with this trip as soon as possible.

– What do you mean? You don’t want to go to the wedding? It’s a historical event!

– I do want to go to the wedding. But I’m tired of this – he waves around – I’m tired of being alert because they don’t know me, and I’m tired of you! – I look at him, just to find his sarcastic, enormous smile. It’s now my time to laugh. He joins me. – Just kidding, of course! I wanted to know if you still are paying attention to me. And you are. Which make me extremely happy.

Coinreruf (II)

– This is the place where you found it? – I asked Rokugan for a deal. He was to bring me to the secret place he found the shell, I was going to teach him about poetry. Words, rhymes and songs to seduce women, more specifically. In silence, we walked from the village to the cliffs, in silence, we went down to a secret beach, climbing down to a very narrow stripe of sand that probably was disappearing when the moon is high. The sea from here was very peaceful, the water clear. The cliffs were almost surrounding us. I close my eyes for a second and I imagine a siren jumping out of the water from the centre of the lagoon, her fishy tail waving salty drops to us. I hear her and I feel the drops. And I open my eyes. Unfortunately, it was just a wave. In front of us, the sun and deeper onto the sea, the reefs where the fishermen get their sustenance. To the left, a short walk from us, there’s an old boat, corroded by the high tides. Long time forgotten, upside down, but I can imagine it can be still used as a shelter in case of storm. Beyond it, after the wall, the docks, basically a bundle of bamboo trunks heavily tied together.

– I’m not cheating you, I promise! – For a moment I thought the big brute was going to go on his knees right there, over the sand. I looked at him. A noble man, and a simple one. His scarce beard was dirty with bread crumps or something. Heavy muscles were visible under the rags he is dressing as a shirt today. The trousers cannot be called this way anymore, so destroyed they are. This people, the are scarce in resources, but they have her. Coinreruf. A goddess on earth.

– I believe in you, my friend. – I grab both shoulders with my hands. I barely manage to cover them, so big they are. – When all of this is over, you will be able to recite so well that you will need to plan the order you want to have them all.

– Have them? Whom? – He asks, in a nervous way. I release him and he goes away like a wild cat, direction the crumbled boat. – The other women? – I nod. He looks at me. His eyes have a determination that I only saw before on wild animals, like the mountain tiger. – I don’t want other women. I want her. Coinreruf. – I see.

– My friend. – I walk close to him, but he evades me again, again, like a wildcat. I wonder if I need to set him a trap to make him reveal me where he get the shells. – I will speak to her when I meet her. I will tell her of your braveness, of your determination, of your quality as a human being. I will tell her that you are a perfect father, a perfect hunter, a beautiful person. – Rokugan smiles, and comes closer. – Unfortunately, I may not manage to change her mind. – Again he sets back. – Women are mysterious beings. But you know that. They hold the mystery of life, and that, my friend, is not so easy. That mystery makes them irrational once per month, and sometimes, cold for the rest of the moon.

– Here it is. – Rokugan is close to the walls opposite to the shipwreck. The clean and goldenly shore disappears there lost between pointy rocks. He goes out of sight for a moment, then, he reappears with something in his hand. – Your shell. – I take it. Indeed it is very beautiful. I resist my impulse to go on my own between the rocks. I caress it. It is smooth, as if polished. Maybe the currents clean it. I put it in my pocket, before my partner decides he wants to keep it. Rokugan eyes are wet. Odd. I look at him, and resist the temptation to touch him again. – Please… now… show me… to sing?

Ashamed of if

I’m reading other blogs. And I’m a little ashamed by the quality of my writings. I know that the art is not simple, it’s not a question of having it or not. You can have it but you don’t know it. Or you don’t have time to polish it. You need to work it out. You need to practise, rest, practise, rest, until you’re able to write down a full paragraph without feeling like you are 5-years old forced to. I need to leave the post to settle down ideally for at least one day before publishing it, and I don’t press the button before reading it again, and cropping it, and reworking it. It’s a lot, if you care. If you want to stay as an active blogger, with a certain quality, not as a passive reader, neither instagram-meat (?) or a twitter-robot (?). And I have my doubts. I was writing before the Internet ever existed, in another language. Alright, that sounds extreme (like if I was alive since the middle age or something) but I will say I was writing well before the Internet was popular where I was living. I was having a paper dairy. Yes I was. And now we have this. I don’t care about having 500 followers, or 30 likes, but it is not nice if you voluntarily post your thoughts on the internet and only a hundred people read it, out of literally billions of them. And if you know you can do it better. Anyway, I don’t have a hundred followers, but a hundred is better than zero, right? So thank you for reading this, tomorrow more of the real thing. If possible, peer reviewed.

Windows XP problems


Yes I know. Windows XP. Out of support. What a thing, right? But we still have some. Specially connected to very expensive devices, like a genome sequencer, an sub-millimeter spectrometer, these things. I don’t get so many devices managed by Linux, and the explanation is simple, the business model. The same that allows to ship right now, devices controlled by an OS from 2001. To migrate all the hardware controllers from XP to Windows 7/10 is not peanuts. For me it is equivalent to translate something from ancient Greek to English. Possible, but not easy. One needs time and money. So what are the problems I encountered using XP on the year 2018?

The main one is the network managing. In the year 2001, internet was a baby. People were using things like the windows messenger. There was no need to connect more than one port to internet. Remember we are not speaking about IoT here. I have this device that uses an Ethernet port to communicate with XP. Then I want XP to come online in addition, and XP stops getting IP from our DHCP. I’m not sure we fixed that as it is written,  but definitely ipconfig /release, ipconfig /renew and reboot were used. That is why my XP was not able to get an IP from my router, maybe.

A similar problem I encountered with another XP controlling a device. The XP was always online (from the beginning?) and it was moved from room to room several times in the last 10 years. Then in the last location, I can’t manage to make it online. Apparently, the TCP connection limit is not enforced, but it may be bound by legal agreement to not permit more than 10 clients. Which means on a big group, like ours, if the machine is widely used, the limit appears quite quickly.

Don’t misunderstand me, at this moment, I like XP. With an XP, I learned the basics of SysAdmin, as well as Visual C++ and I built my first GUI. But you can’t live in the past, and right now, XP is the past. The problem is that you can’t easily move ahead, not without money. Money makes the world go round…

The water wedding (XXII)

– This is going to be very difficult for me. – We just dressed and started the engine again. The break I did was exactly what I was needing to adjust my empathy levels. – Kris, I know you, and I know you’re trying to cope with the changes I triggered, but on this life, one needs to understand that there is a moment when you have no choice but embrace the changes. – I nod. – As your superior officer, from now on I forbid you to use your nanobots unless they are really needed.

– Why is that? – I’m focused on the road. I’m looking forward to reach the Golden Towers, somehow I feel like now I will understand more about what they are, what they mean, than before when I started the trip. And now I get this weird order.

– Although they don’t always know what they say, the Imperial Guard has sensors. And they will be triggered if you use your enhancements. I can’t prove that to you, so you need to trust me. – I turn my head to look at him for a second. Hakim is facing the infinite, like remembering something sad that happened long time ago. I’m tempted to ask what does it mean trust for him, then he continues. – I love you, Kris. I told you. But this world we live, this Empire, is not fair for everybody. You may think the Emperor and the Empress are the ones with the power to decide what you can have and what you can’t. Or maybe the Court. The truth is, they don’t have such a power. We have. The future is ours, we have the right to decide what we do with it.

– I understand. – And I do, and I seem to recall now that Hakim spoke this way before, when I didn’t have the nanos to help me to process the information. – A position of power can result on an abuse of power.

– Right. Is that the nanocites speaking, or does it come from Kris? – I hit his head with my hand. – Ouch. Just joking. I will add something to your digression. This is what we call the power loop. You make somebody powerful and this person will abuse of that. You need some kind of control. So, enlight me Kris, how can we escape from the power loop?

– I don’t know. – I sort out a big hump on the road. We both jump from our sits synchronously, like toys out of a spring box. I think I should laugh at the picture, but I can’t. So I continue like if nothing happened. – I suppose… the only way to escape is to hide this power from the others, so the others will not realize the subject has power.

– Very good. The so called “power in the shadow”. Well, we need to be that power, Kris. We need to watch that our little world, that is, the Empire, does survive the current crisis. And by crisis I mean the wedding…

The water wedding (XXI)

Something is definitely different on me. While we drive through the Forest of the Tree Men, I seem to perceive each of the arboreal humans that pullulate in the green like a shinny dot on my peripheral view. Sometimes, when they are too close, like directly over us, I even see the shape of them, superimposed like a moving chalk drawing over the trees. I don’t mention about my new sense to Hakim, that seems to be deep into his own thoughts. Besides, maybe he’s even feeling them also.

There are so many questions now. And so few answers. I wonder why I didn’t ask myself before what is my purpose in the world. Why we live under the rule of the Emperor, when he/she doesn’t even know about our existence. Well, they know now, we are going to his wedding, but that’s secondary. Why we can’t travel freely through the world. I seem to know now that it’s because something called radiation. Why we fight the System. Why we don’t have technology, but some of us have. Is it because we don’t know how to make new things anymore. It is funny how the answers come to me, there’s a tickle somewhere in my head and there I have it.

The Tree Men, are they human? From the silhouette, I could say yes. They have two arms, two legs, and a head. A funny shaped head, but a head. I try to probe mine, try to get the tickle. The tickle on the back of my brain. It’s not actually on the back, but on the limbic cortex, also known as the lizard brain. They, the nanobots, are building their emergency systems there, thanks for the info. Building status, 89 percent. Also irrelevant. I remember Hakim saying me that I will be able to communicate with them in a way, maybe he was referring to this. Question: how long until we reach the Golden Towers? Answer: it’s three hundred klicks away, so at least five hours. I now have acquired also a superior sense of time and space, I know we need to use patterns to be sure we measure the same. The pattern of time is the second, that is more or less lasting a breath. The pattern of space is the meter. I’m one point sixty seven. My arm is more or less half a meter long. All of this is not interesting, but practical.

– Don’t you want to make a break? – Hakim. My master, my lover, my partner. – You have been driving like crazy for the last two hours or so. I’m impressed, by the way, you did not even get close to collide to anything in our way. When we crossed that green tree tunnel, like half an hour ago, I was tempted to ask you to reduce the speed…but then I saw your look. – A break. Why not? I reduce the auto speed, and look at him. – You look different. The nanobots are speaking to you, right?

– Yes. I know now more precisely where we are and where we go. – Hakim smiles the smile I love, but now I don’t feel the same when I see it. It may be my new brain. Yes it is. Now I’m more rational. – We are three hours away from the Golden Towers.

– That’s fantastic! So we can indeed make a break. Are you now fully reconfigured? – I understand what he says immediately.

– 89 percent. – I ask my lizard brain. No, they are not going to be done any time soon.

– 89. Nice number. You know, I can feel you nanobots. They want to speak to mine. But they can’t unless they are fully installed. And unless you leave them do so. – I break the car. After all, it doesn’t matter where we park: there’s rarely traffic through this road anyway. – What I mean, Kris, is that they do change you, but you don’t need to change. Yes, I know what you are going to say. They are indeed cannibalising somehow your limbic cortex. Where the emotions live. But they don’t destroy it, they improve it, so that you will be able to feel joy if you want… or pleasure, by the way. This change is good, not bad. So don’t let them change you, I mean, don’t let the new powers change you. You are nice as you are. Please don’t change, even if the world is changed. Please. – He puts his hand in my cheek. I grab it, and I get closer to him, and we kiss.