s.chauhan
Posts: 1
Joined: Tue Jun 15, 2021 9:28 pm

How to use tkinter with MicroPython

Tue Jun 15, 2021 9:43 pm

I recently started working with raspberry pi pico and i want to integrate SD101201 hall effect Sensor which can be used to calculate speed and direction of the rotation . I want to use tkinter but when i try to run a program it shows "ImportError: no module named 'tkinter'" any suggestions?

I am using Thonny.

dbrion06
Posts: 511
Joined: Tue May 28, 2019 11:57 am

Re: How to use tkinter with MicroPython

Wed Jun 16, 2021 11:08 am

micropython is for microcontrollers, who have very limited resources, much less than a RPi.
I bet tkinter needs more resources than a pico rp2040 can offer and therefore it has not been ported..

If you go to the pico rp2040 dedicated section viewforum.php?f=146, you will see that some screens (ss1306, say) are both supported by c and python; but they are very limited (in number and functionalities).

either you use pico pi to interface to some hardware and you try to process the result on a RPi (classico), or you really should go to this part of the forum, where you can get some help dedicated to the pi pico ...

Edited : i tried to have (if moderators agree) to have this thread moved to the rpi pico rp2040 subforum (it is interesting, and odds you get help are greater)

jamesh
Raspberry Pi Engineer & Forum Moderator
Raspberry Pi Engineer & Forum Moderator
Posts: 29062
Joined: Sat Jul 30, 2011 7:41 pm

Re: How to use tkinter with MicroPython

Wed Jun 16, 2021 1:25 pm

For tkinter to be relevant you also need to display the GUI - how are you planning to do that?

And even then, tkinter requires an underlying windowing system (e.g. Windows, X windows), which Pico doesn't have.
Principal Software Engineer at Raspberry Pi (Trading) Ltd.
Working in the Application's Team.

fdufnews
Posts: 344
Joined: Fri Oct 07, 2011 5:37 pm

Re: How to use tkinter with MicroPython

Wed Jun 16, 2021 1:47 pm

You'd better look on the Micropython forum. For example here.
There are some drivers sometimes for other plateform than Pico but it is not that difficult to adapt the drivers (maybe they can be used as is). They usually are inheriting from the framebuffer class which offers some basic functions to draw on screen.
There is also a more elaborated library from @pythoncoder that can probably work on the Pico platform.

hippy
Posts: 10322
Joined: Fri Sep 09, 2011 10:34 pm
Location: UK

Re: How to use tkinter with MicroPython

Wed Jun 16, 2021 2:05 pm

A Pico isn't a Pi or PC and MicroPython isn't Python. It is therefore not currently possible to run tkinter on a Pico.

It should be possible to provide a tkinter equivalent for a Pico but graphics tend to use quite a lot of memory and the the Pico has very little for such applications. Though it could be done I don't see it happening.

The three alternatives are -

1) Alter your code to use 'print' statements rather than whatever the tkinter code uses; go for text output rather than graphical.

2) Alter your code to use frame buffers and/or direct memory access to provide you graphical interface,or use some other graphical library available for the Pico.

3) Divide your code into two; have the Pico send its data to a Pi or PC and have that use tkinter to display the graphics.

That last option (3) is the one which makes most sense to me if you must have a graphical output. Rather than read raw sensor data, changing that to use what comes from the Pico, should be a fairly easy change to make. The Pico code would pretty much only be what's needed in (1).
Last edited by hippy on Wed Jun 16, 2021 2:11 pm, edited 1 time in total.

PiGraham
Posts: 4795
Joined: Fri Jun 07, 2013 12:37 pm
Location: Waterlooville

Re: How to use tkinter with MicroPython

Wed Jun 16, 2021 2:11 pm

I should think Tkinter is dependent on an operating system which pico doesn't have.
A search for micropython GUI might get you started.

e.g.
https://github.com/peterhinch/micropython-tft-gui
Provides a simple touch driven event based GUI interface for the Pyboard when used with a TFT display. The latter should be based on SSD1963 controller with XPT2046 touch controller. Such displays are available in electronics stores e.g. and on eBay. The software is based on drivers for the TFT and touch controller from Robert Hammelrath.

It now uses and requires uasyncio V3.

It is targeted at hardware control and display applications.
Image

hippy
Posts: 10322
Joined: Fri Sep 09, 2011 10:34 pm
Location: UK

Re: How to use tkinter with MicroPython

Wed Jun 16, 2021 2:36 pm

PiGraham wrote:
Wed Jun 16, 2021 2:11 pm
I should think Tkinter is dependent on an operating system which pico doesn't have.
Technically it doesn't require an OS, but it does rely on other libraries and calls which ultimately reach the OS. It would be possible to divert calls so they never reached the OS, thus never needs an OS.

But that is undoubtedly a lot of work. A better approach is to create a port of tkinter which offers the exact same functionality but delivers that in a different way, more suited to what it is running on.

Of course one can then argue whether, what looks exactly like tkinter from the user's perspective, is actually tkinter or not.

Like delivering 'RPi.GPIO' and 'gpiozero' on a Pico, delivering tkinter should be no different. Just an awful lot more work and effort with even less need for doing that.

If I were going to deliver 'tkinter' for a Pico I would create something which did little more than pass what was wanted over USB and have a host deliver the actual functionality to display as desired.

Something which allows a Pico to easily interact with graphics or a GUI on a host would be very useful IMO. Tkinter might just be a layer on that.

User avatar
scruss
Posts: 4191
Joined: Sat Jun 09, 2012 12:25 pm
Location: Toronto, ON
Contact: Website

Re: How to use tkinter with MicroPython

Wed Jun 16, 2021 2:42 pm

hippy wrote:
Wed Jun 16, 2021 2:36 pm
Something which allows a Pico to easily interact with graphics or a GUI on a host would be very useful IMO. Tkinter might just be a layer on that.
Like Firmata, perhaps. Though it would be a waste of the Pico's processing power for it just to act as a simple I/O handler.
‘Remember the Golden Rule of Selling: “Do not resort to violence.”’ — McGlashan.
Pronouns: he/him

dbrion06
Posts: 511
Joined: Tue May 28, 2019 11:57 am

Re: How to use tkinter with MicroPython

Wed Jun 16, 2021 6:30 pm

Scruss Analogy with firmata gave me an idea:
in viewtopic.php?f=91&t=313958
joao linked with http://abyz.me.uk/picod/
examples are very simple, and I guess they can be easily interfaced with tkinter (or pycurses + python3 mathplotlib : has very nice curve plotting abilities ).
w/r waste of processing power: pico are very cheap, cheaper than Arduini and I must confess I "only" use one core of them... perhaps OP can live happily with half a pico being exposed to a PC/Rpi

User avatar
OneMadGypsy
Posts: 326
Joined: Wed Apr 28, 2021 1:57 am
Location: New Orleans, Louisiana
Contact: Website

Re: How to use tkinter with MicroPython

Wed Jun 16, 2021 8:24 pm

If you have a raspberry pi it is very easy to connect UART from the Pi to the Pico and use tkinter on the Pi side to control/display stuff from the pico side. Before I built a game controller I was using a ribbon cable breakout from the Pi400 to a breadboard with various pins jumped to the pico, and the below tkinter script. It worked fine as long as the tkinter window had focus. Obviously, if I would have used UART it would have been a lot less wires, but I knew it was just a temporary solution, so I wasn't too worried about optimizing the setup. Basically, in this case, tkinter was just a very simple way to capture keyboard press/release actions and pull pins high or low upon them.

Code: Select all

import tkinter as tk, RPi.GPIO as GPIO, time

#__> Initiate tkinter and configure root
root = tk.Tk()
root.geometry('240x40+300+300')
root.resizable(False, False)
root.title('Controls')
root.configure(bg='black', highlightthickness=0)
root.grid_columnconfigure(0, weight=1)
for r in range(2):
    root.grid_rowconfigure(r, weight=1)

#__> Create a simple reminder message
cfg = dict(fg='#DDDDDD', bg='black', font='Helvetica 12 bold')
tk.Label(root, text='This window must have focus', **cfg).grid()
tk.Label(root, text='to register keypresses'     , **cfg).grid()

#__> Initialize RPi.GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
   
#__> ARROW KEYS ~ UP:17  DOWN:22  LEFT:23  RIGHT:27 ~ according to BCM pin numbers
#__> Key press and key release are automatically managed
for action, cmd in zip(['KeyPress', 'KeyRelease'], [False, True]):
    for key, pin in zip([f'<{action}-Up>', f'<{action}-Down>', f'<{action}-Left>', f'<{action}-Right>'], [17, 22, 23, 27]):
        #initialize pins
        if not cmd:
            GPIO.setup(pin, GPIO.OUT)
            GPIO.output(pin, True)
        #bind arrow keys
        root.bind(key, lambda e, p=pin, c=cmd: GPIO.output(p, c))

#__> EXTRA KEYS
#__> Key press and key release are automatically managed
for action, cmd in zip(['KeyPress', 'KeyRelease'], [False, True]):
    for key, pin in zip([f'<{action}-space>', f'<{action}-BackSpace>', f'<{action}-Return>'], [24, 25, 4]):
        #initialize pins
        if not cmd:
            GPIO.setup(pin, GPIO.OUT)
            GPIO.output(pin, True)
        #bind extra keys
        root.bind(key, lambda e, p=pin, c=cmd: GPIO.output(p, c))

#__> Keep tkinter alive        
root.mainloop()
"Focus is a matter of deciding what things you're not going to do." ~ John Carmack

PiGraham
Posts: 4795
Joined: Fri Jun 07, 2013 12:37 pm
Location: Waterlooville

Re: How to use tkinter with MicroPython

Thu Jun 17, 2021 7:24 am

No clues were given on what display device should display a ykinter GUI. Ecept that mention of Thonny:
s.chauhan wrote:
Tue Jun 15, 2021 9:43 pm
I recently started working with raspberry pi pico and i want to integrate SD101201 hall effect Sensor which can be used to calculate speed and direction of the rotation . I want to use tkinter but when i try to run a program it shows "ImportError: no module named 'tkinter'" any suggestions?

I am using Thonny.
One possibility is that the GUI shows up on the machine running Thonny, which is where the all GUI is. In that case run a GUI program on the host that communicates with the Pico to get the sensor data. Probably Use USB serial to send the data.

Potentiallt it might be possible to uSB Ethernet on the Pico, run a TCP/IP network stack and X-Windows client and talk to an X-Server on the host machine.That sounds hard.

The more natural assumption was a display attached to the Pico itself. That could be a small LCD or OLED showing a minimal UI. several links to that sort of thing have been posted.

Another option is to use the VGA adaptor boards to connect to a high res monitor and that's where it gest difficult.

hippy
Posts: 10322
Joined: Fri Sep 09, 2011 10:34 pm
Location: UK

Re: How to use tkinter with MicroPython

Thu Jun 17, 2021 11:32 am

PiGraham wrote:
Thu Jun 17, 2021 7:24 am
One possibility is that the GUI shows up on the machine running Thonny
Having Thonny produce a virtual graphics display may be the pragmatic solution. Thonny already supports a graph plotter which intercepts data sent from the Pico and other devices; logging to files and displaying graphics would just be extensions to that.

One could start with a simple PyGame surface and only allow the Pico to set the colour of single pixels. That's going to be slow if the Pico has to set every pixel separately but one can allow 'macro commands' to be sent to have the host draw a line or circle, render text. One just keeps adding such 'macro commands' until even tkinter is supported on a Pico.

Using virtual serial ports and 'print' is the fast-track to things working but there's no reason other transport mechanisms couldn't be used.

Code: Select all

def SetPixel(x, y, color):
  print("Display:SetPixel {}, {}, {}".format(x, y, color))
Done properly this can be done within Thonny and also made available as a cross-platform application. The hard part will probably be agreeing an API. I would suggest implementing the PyGame API on a Pico would be a good starting point. Get that working then refine it, optimise.

That would also cater for 'PyGame' on a Pico with a local display, LCD, OLED, VGA, HDMI, composite. Having a singular well defined and already documented API is IMO much better than the diversity of incompatible drivers API's one usually ends up with.

For one thing it would allow PyGame code written to run on a Pi to run on a Pico 'as is'. Reducing the barriers to using a Pico should be a priority if pushing the Pico into educational settings and home programmer hands.

So; something else to add to my To Do list.

PiGraham
Posts: 4795
Joined: Fri Jun 07, 2013 12:37 pm
Location: Waterlooville

Re: How to use tkinter with MicroPython

Thu Jun 17, 2021 11:59 am

hippy wrote:
Thu Jun 17, 2021 11:32 am
...only allow the Pico to set the colour of single pixels. That's going to be slow if the Pico has to set every pixel separately but one can allow 'macro commands' to be sent to have the host draw a line or circle, render text. One just keeps adding such 'macro commands' until even tkinter is supported on a Pico.
'm not sure that makes much sense if you have a machine that can run Thonny then write your GUI to run on that machine and write some simple non-GUI code in micropython to run on the Pico and just send the data to the GUI app. Example template apps for sensor and GUI parts would help there

User avatar
scruss
Posts: 4191
Joined: Sat Jun 09, 2012 12:25 pm
Location: Toronto, ON
Contact: Website

Re: How to use tkinter with MicroPython

Thu Jun 17, 2021 9:27 pm

dbrion06 wrote:
Wed Jun 16, 2021 6:30 pm
joao linked with http://abyz.me.uk/picod/
picod is very neat, but it's not compatible with Firmata. Firmata has been around for ages — it was mature, possible even elderly, when I wrote about it in The MagPi in 2012 — and there's quite a bit of creative technology/interaction design software that assumes that "I can talk to Arduino" means "I know how to speak Firmata".
‘Remember the Golden Rule of Selling: “Do not resort to violence.”’ — McGlashan.
Pronouns: he/him

hippy
Posts: 10322
Joined: Fri Sep 09, 2011 10:34 pm
Location: UK

Re: How to use tkinter with MicroPython

Fri Jun 18, 2021 12:15 pm

PiGraham wrote:
Thu Jun 17, 2021 11:59 am
hippy wrote:
Thu Jun 17, 2021 11:32 am
...only allow the Pico to set the colour of single pixels. That's going to be slow if the Pico has to set every pixel separately but one can allow 'macro commands' to be sent to have the host draw a line or circle, render text. One just keeps adding such 'macro commands' until even tkinter is supported on a Pico.
'm not sure that makes much sense if you have a machine that can run Thonny then write your GUI to run on that machine and write some simple non-GUI code in micropython to run on the Pico and just send the data to the GUI app. Example template apps for sensor and GUI parts would help there
Definitely if that's what one wants to do but providing the Pico with graphic primitives makes it easier to write code which can display on a host or on a locally attached display, simply by setting a flag.

I don't think it's a case of one way or the other, but what's best or most suitable for the user. Ultimately one would be able to just 'pass the data' whether the GUI and templates are on a host or on a Pico, but there would be a lot of work needed to get to that.

One problem with the adoption of MicroPython, perhaps not so much with CircuitPython, is people write graphics drivers for a display and invent their own API's, often incompatible with other display drivers, then expect users to use those. That's understandable because MicroPython has historically run on constrained boards and used to create specific projects; wanting to use some other driver has been deemed a problem for the user to solve.

The Pico is somewhat different in the hands of students and home users; it is a more generic microcontroller, far less constrained, not just a single project device. Many see it more as a 'Small Pi' and expect to use it that way, expect code to run with any display without changing their code beyond specifying what's being used. The abstraction layer which allows that doesn't exist and I believe it should.

'SetPixel' is the fundamental graphic primitive upon which any graphics are built which is why I would start with that.

I have never been a fan of having to change code to make it run on some other thing. I believe that in an ideal world one should be able to take any code and run it on anything without change. That is not achievable in practice but moving in that direction is how I think things should go.

PiGraham
Posts: 4795
Joined: Fri Jun 07, 2013 12:37 pm
Location: Waterlooville

Re: How to use tkinter with MicroPython

Tue Jun 22, 2021 8:43 am

hippy wrote:
Fri Jun 18, 2021 12:15 pm

One problem with the adoption of MicroPython, perhaps not so much with CircuitPython, is people write graphics drivers for a display and invent their own API's, often incompatible with other display drivers, then expect users to use those. That's understandable because MicroPython has historically run on constrained boards and used to create specific projects; wanting to use some other driver has been deemed a problem for the user to solve.
That's a good point, but then surely the thing to do is to adopt an existing graphic library rather than invent one's own by addressing pixels.
And if the display device is in fact the machine running Thonny, then the graphic libraries are very well established and all the more reason to not address pixels on the Pico.

User avatar
OneMadGypsy
Posts: 326
Joined: Wed Apr 28, 2021 1:57 am
Location: New Orleans, Louisiana
Contact: Website

Re: How to use tkinter with MicroPython

Tue Jun 22, 2021 11:29 am

I have never been a fan of having to change code to make it run on some other thing. I believe that in an ideal world one should be able to take any code and run it on anything without change.

In an ideal world that will never happen. That's some kind of totalitarian view where nothing ever gets better because it is constrained by the limits of being compatible with the past. At the very least it creates a very bloated system as you try to be compatible with the past while also trying to provide the future (Windows).

One-size-fits-all doesn't really fit anybody, and it falls apart faster than this-size-fits-you.


Code should run where it is intended to run, and it generally shouldn't intend to run everywhere (Java), because it will either fail to utilize the full power available to it or be so bloated and inefficient it begins to negate it's own purpose in performance.
"Focus is a matter of deciding what things you're not going to do." ~ John Carmack

hippy
Posts: 10322
Joined: Fri Sep 09, 2011 10:34 pm
Location: UK

Re: How to use tkinter with MicroPython

Tue Jun 22, 2021 1:47 pm

PiGraham wrote:
Tue Jun 22, 2021 8:43 am
hippy wrote:
Fri Jun 18, 2021 12:15 pm

One problem with the adoption of MicroPython, perhaps not so much with CircuitPython, is people write graphics drivers for a display and invent their own API's, often incompatible with other display drivers, then expect users to use those. That's understandable because MicroPython has historically run on constrained boards and used to create specific projects; wanting to use some other driver has been deemed a problem for the user to solve.
That's a good point, but then surely the thing to do is to adopt an existing graphic library rather than invent one's own by addressing pixels.

And if the display device is in fact the machine running Thonny, then the graphic libraries are very well established and all the more reason to not address pixels on the Pico.
Indeed, and no doubt why the OP wanted to know how to use tkinter which is provided with the standard Python installation.

We should be providing standard graphics libraries but the problem is that's not being done, everyone is reinventing their own wheel.
OneMadGypsy wrote:
Tue Jun 22, 2021 11:29 am
I have never been a fan of having to change code to make it run on some other thing. I believe that in an ideal world one should be able to take any code and run it on anything without change.
In an ideal world that will never happen. That's some kind of totalitarian view where nothing ever gets better because it is constrained by the limits of being compatible with the past.
I disagree. It is entirely possible to remain backwards compatible while going forward.
OneMadGypsy wrote:
Tue Jun 22, 2021 11:29 am
Code should run where it is intended to run, and it generally shouldn't intend to run everywhere (Java), because it will either fail to utilize the full power available to it or be so bloated and inefficient it begins to negate it's own purpose in performance.
I believe having to change code for everything it runs on is worse than the negatives of facilitating running that code 'as is'. And I don't believe there are such negatives in most cases.

In most cases it's not that something couldn't run code 'as is' for something else, but someone chose to implement things differently which precluded dong that. It is likely little different no matter which way it was done, just that one way creates zero effort for the end-user and the other a huge amount of work.

For example, anyone wanting to use an existing MicroPython UART using library on a Pico can't unless they modify that library. That is work which has to be done which wouldn't have even been necessary if the Pico hadn't chosen to do things differently.

If you can't see the disadvantage of library code needing to use "printf" on one thing, "?", "say" and "PRINT" on another, can't see the benefits of some standardised 'print' naming; I guess we are on completely different wavelengths. I couldn't even begin to support the notion that things should be different depending on the target.

GCC's incredible success seems to me to be entirely down to being able to take code and have it run on anything without having to change that code. Programmers can write their code once and it can run on anything. That's how I think it should be.

jamesh
Raspberry Pi Engineer & Forum Moderator
Raspberry Pi Engineer & Forum Moderator
Posts: 29062
Joined: Sat Jul 30, 2011 7:41 pm

Re: How to use tkinter with MicroPython

Tue Jun 22, 2021 2:18 pm

hippy wrote:
Tue Jun 22, 2021 1:47 pm
GCC's incredible success seems to me to be entirely down to being able to take code and have it run on anything without having to change that code. Programmers can write their code once and it can run on anything. That's how I think it should be.
That nothing to do with GCC and everything to do with the C standard that GCC adheres to.
Principal Software Engineer at Raspberry Pi (Trading) Ltd.
Working in the Application's Team.

User avatar
OneMadGypsy
Posts: 326
Joined: Wed Apr 28, 2021 1:57 am
Location: New Orleans, Louisiana
Contact: Website

Re: How to use tkinter with MicroPython

Tue Jun 22, 2021 3:21 pm

For example, anyone wanting to use an existing MicroPython UART using library on a Pico can't unless they modify that library. That is work which has to be done which wouldn't have even been necessary if the Pico hadn't chosen to do things differently.

That one sentence right there makes my case as to why things shouldn't be built generically to work on everything. I am not intimately familiar with the Pico UART system so, I am going to make some assumptions, and even if my assumptions are incorrect they still hold water in the spirit of what they imply. First off, why were things chosen to be different for the Pico? When you have a giant organization that makes some of the most popular boards on the planet I find it hard to believe they are cutting some corner. Either the UART is the way it is because it has to be or some genius involved with making the board made some advancement that currently only Pico users get to utilize. This is exactly why one-size-fits-all code is a bad idea. If the case is the former of what I said other codes don't work because they didn't plan for some deficiency or peculiarity. If it's the latter, other codes don't work because they aren't prepared for the future or any possible advancements that may be implemented.

I think it's great that you have to be highly skilled and competent to program a bunch of non-generic devices in a non-generic way. I don't use anybody else's codes, beyond what is supplied as the base of micropython for the Pico, and even that is heavily modified. I couldn't even imagine slapping together a bunch of arbitrary scripts and trying to call it a thing. The day where your version of a "perfect world" happens, you can just hang up your keyboard and forget about programming entirely. The generic and soulless world you desire will reverse engineer itself and obsolete you entirely. Originality is what brought you everything that is available to you in this world. Having to actually do work is what gives things value.

We're absolutely not on the same wavelength. This is practically Capitalism vs Communism. I believe YOU should work for what you want. You believe "The State" should provide an approved method that everyone can follow so we can all be on a level playing field. We are not all on a level playing field, though. Dumbing down the entire system so noobs can skip the "hard work" and "dedication" part is a terrible idea, because it's the hard work and dedication parts that give you the deep understanding and experience to make things better. Go to stackoverflow and start reading questions for butt-simple languages like python. Things are already dumbed down and generic, to some degree, and the newbies are still struggling. Some of them are struggling to successfully ask a question.

Dumbing down the world for starters isn't doing anyone any favors. You'll never dumb it down enough. People will just get dumber in proportion to how simple you make it.
"Focus is a matter of deciding what things you're not going to do." ~ John Carmack

hippy
Posts: 10322
Joined: Fri Sep 09, 2011 10:34 pm
Location: UK

Re: How to use tkinter with MicroPython

Tue Jun 22, 2021 6:37 pm

OneMadGypsy wrote:
Tue Jun 22, 2021 3:21 pm
For example, anyone wanting to use an existing MicroPython UART using library on a Pico can't unless they modify that library. That is work which has to be done which wouldn't have even been necessary if the Pico hadn't chosen to do things differently.
That one sentence right there makes my case as to why things shouldn't be built generically to work on everything.
I don't think it does but it seems we have very different views on standardisation and the benefits of standardisation. I see it as a very good beneficial thing you seem to see it as a bad thing. I doubt we will ever agree.
OneMadGypsy wrote:
Tue Jun 22, 2021 3:21 pm
First off, why were things chosen to be different for the Pico? When you have a giant organization that makes some of the most popular boards on the planet I find it hard to believe they are cutting some corner.
I have no idea but the MicroPython port wasn't created by a giant organisation but the small MicroPython team. They did get help and possibly some funding but they put in the work and presumably made the decisions.

I don't know why they decided the UART API would be different to how it is on other boards. My guess would be they didn't think about it or the consequences. I am not convinced they have much interest in standardisation or compatibility given they decided 'time.localtime()' would return a different sized tuple than Python does which means Python libraries and code using that won't run on MicroPython without change.

If they aren't interested in standardisation and compatibility with in-built Python modules it perhaps follows they would care even less for non-standard stuff.
OneMadGypsy wrote:
Tue Jun 22, 2021 3:21 pm
The day where your version of a "perfect world" happens, you can just hang up your keyboard and forget about programming entirely. The generic and soulless world you desire will reverse engineer itself and obsolete you entirely. Originality is what brought you everything that is available to you in this world. Having to actually do work is what gives things value.
I would say that wasting time when that time does not need to be wasted, having to adjust one thing which works so it works on some other thing, detracts value.

I would not characterise my perfect world as "soulless" but "vibrant" and "welcoming", allowing people to learn how to do something and get on with doing it without having to repeatedly learn how to do it on each thing they encounter.

I am sure we all consider surgeons to be valuable assets and their value is measured in how many lives they improve or save. Can you imagine how much less value they would have if instead of doing surgery they were wasting time reading the instruction manuals because today's scalpel is different to the one they normally use. Not better, just different, unfamiliar, that's value removed.
OneMadGypsy wrote:
Tue Jun 22, 2021 3:21 pm
We're absolutely not on the same wavelength. This is practically Capitalism vs Communism. I believe YOU should work for what you want. You believe "The State" should provide an approved method that everyone can follow so we can all be on a level playing field.
That's quite a conclusion when I am merely not wanting to waste my time when I could be doing something else which delivers more value to the world.

I don't want to be wasting my time reinventing wheels when I could be improving the wheel. For example; suppose I want to add some amazing new functionality to an existing C library. I add it, and everyone can use it. If I do that for a MicroPython library it's not just adding it, there's extra effort if it has to be implemented differently across MicroPython boards.
OneMadGypsy wrote:
Tue Jun 22, 2021 3:21 pm
Dumbing down the entire system so noobs can skip the "hard work" and "dedication" part is a terrible idea ...

Dumbing down the world for starters isn't doing anyone any favors. You'll never dumb it down enough. People will just get dumber in proportion to how simple you make it.
I don't consider it dumbing down but making people more productive.

Take that Thumb 2 Execution Engine I have been working on in the past few days. I got that working as a C Extension Module. Job Done. Not quite; because the Native C Module doesn't accept the same source code, doesn't use the same ABI. If it had accepted the same code had the same ABI it would have been done in seconds. Because it was different there was a whole lot of extra work to do. And that took time I could have spent doing something else, something which could have been more useful to others.
Last edited by hippy on Tue Jun 22, 2021 7:03 pm, edited 1 time in total.

hippy
Posts: 10322
Joined: Fri Sep 09, 2011 10:34 pm
Location: UK

Re: How to use tkinter with MicroPython

Tue Jun 22, 2021 6:58 pm

Back to running a GUI on the host. Here's my proof of concept.

On the Pi host - a PyGame-centric display driver reading from serial port -

Code: Select all

#!/usr/bin/python

import os
import pygame
import serial
import sys
import time

python3 = sys.version_info.major >= 3

def GetCommand():
  while True:
    if python3:
      ba = comPort.readline()
      s  = ""
      for b in ba:
        s = s + chr(b)
    else:
      s = comPort.readline()
    if False:
      print("Received : {}".format(s.rstrip()))
    if s.startswith("PyGame,"):
      a = s.rstrip().split(",")
      args = []
      for arg in a[2:]:
        args.append(int(arg))
      return a[1], args

def FindDisplayDriver():
  for driver in ["fbcon", "directfb", "svgalib"]:
    if not os.getenv("SDL_VIDEODRIVER"):
      os.putenv("SDL_VIDEODRIVER", driver)
    try:
      pygame.display.init()
      return True
    except pygame.error:
      pass
  return False

def Main(port):
  def at(h, w):
    return (w, height - h)
  pygame.init()
  if not FindDisplayDriver():
    print("Failed to initialise display driver")
  else:
    if True:
      width  = 320
      height = 240
      screen = pygame.display.set_mode((width,height))
    else:
      width  = pygame.display.Info().current_w
      height = pygame.display.Info().current_h
      screen = pygame.display.set_mode((width,height) , pygame.FULLSCREEN)
      pygame.mouse.set_visible(False)
    image = pygame.Surface((width,height))
    image.fill(0)
    cmd, data = GetCommand()
    while cmd != "Q":
       if cmd == "L":
         hfrom, wfrom, hto, wto, r, g, b = data
         pygame.draw.line(image, (r,g,b), at(hfrom,wfrom), at(hto,wto))
       elif cmd == "S" :
         h, w, r, g, b  = data
         image.set_at(at(h,w), (r,g,b))
       elif cmd == "U" :
         screen.blit(image,(0,0))
         pygame.display.update()
       elif cmd == "F":
         r, g, b = data
         image.fill((r,g,b))
       cmd, data = GetCommand()
    time.sleep(5)
    pygame.quit()

if __name__ == "__main__":
  comPort = serial.Serial("/dev/ttyACM1")
  Main()
On the Pico - a program which sends commands to the host; "F" fill, "L" line draw, "U" update host display -

Code: Select all

import _ttyacm
import time

TxByte = _ttyacm.txbyte_itf1

def Tx(*args):
    s = "PyGame"
    for arg in args:
        s = s + "," + str(arg)
    if False:
        print("Send : {}".format(s))
    for c in s:
        TxByte(ord(c))
    TxByte(0x0D)
    TxByte(0x0A)
    time.sleep(0.1)
    
width  = 320
height = 240

Tx("F", 0, 0, 255)
Tx("U")
for h in range(height):
  Tx("L", h, 0, h, h * width // height, 0, 255, 0)
  Tx("U")
for h in range(height):
  Tx("L", height - h, 0, height - h, h * width // height, 255, 0, 0)
  Tx("U")
The fastest I got that combo to draw the image - update per line taken out - was just shy of a minute. Not great but it worked, and I am sure it can be improved.

Probable reasons for slowness -
  • Nothing is optimised.
  • Data transfers aren't minimised.
  • I am sending pure text lines so I have encoding and decoding time.
  • I had to include a time.sleep(0.1) after every line sent or the data stream got corrupted.
  • My send routine is a byte at a time
  • Every byte sent invokes a flush.
  • Each byte is probably a single USB transaction.
  • I am using Python for the host program.
  • I am using MicroPython rather than call a C Module on the Pico.
It can set an individual pixel, draw a line, fill the screen, and doing more is just a case of adding a new command and having the host code do what's asked, pushing that command from the Pico.

Update : My serial TX buffer is 256 bytes. Optimising my time.sleep(0.1) to only occur after about 250 bytes have been sent, avoids corruption of the stream and gets the drawing time down to 15 seconds.

Later update : The data stream getting corrupted suggested my underlying code for talking over USB virtual serial ports from the Pico was flawed, and indeed it was. So, if nothing else, this excursion has led me to fix that and add sending strings. Drawing time is now down to 8 seconds.
Last edited by hippy on Thu Jun 24, 2021 6:14 pm, edited 1 time in total.

PiGraham
Posts: 4795
Joined: Fri Jun 07, 2013 12:37 pm
Location: Waterlooville

Re: How to use tkinter with MicroPython

Wed Jun 23, 2021 7:34 am

hippy wrote:
Tue Jun 22, 2021 6:58 pm
Back to running a GUI on the host. Here's my proof of concept.

On the Pi host - a PyGame-centric display driver reading from serial port -
That makes no sense to me. Why do any graphics code at all on the Pico when you have PyGame and a rich choice of graph plotting and WIMPS UI libraries etc on the host?
Just send the core data from the Pico and run the GUI entirely on the host.

If you want to drive a display attached to the Pico use a lightweight graphics library on the Pico.

hippy
Posts: 10322
Joined: Fri Sep 09, 2011 10:34 pm
Location: UK

Re: How to use tkinter with MicroPython

Wed Jun 23, 2021 10:51 am

PiGraham wrote:
Wed Jun 23, 2021 7:34 am
That makes no sense to me. Why do any graphics code at all on the Pico when you have PyGame and a rich choice of graph plotting and WIMPS UI libraries etc on the host?
Just send the core data from the Pico and run the GUI entirely on the host.
I fear we risk going round in circles - viewtopic.php?p=1879177#p1879177

It is not necessarily about what would be best but catering for how a user wants or chooses to do it. This was merely an attempt to show it could easily be done by using graphics primitives.

It is also not just about what we consider best but what a user considers best. With a graphics primitive approach the user only needs one host program and they can draw anything they want to that by altering their Pico code. With a core data transfer approach they need to update the Pico code and host program. Which a user prefers is up to them.

Of course things would be equal if we had a core data transfer host program which was flexible enough that it did not need to change when the user added new core data to be displayed. But we don't have that, and it's a far bigger effort to provide that than writing a host program which can handle graphics primitives.

Plus, if using the graphics primitive approach to display on a host, those primitives can easily be redirected to a local display driver with a simple shim bridging them if that was desired. Using the core data transfer approach they would need to replicate all the host program was doing before they could use a local display.

Each approach has its advantages and disadvantages.

What we have with my proof of concept code, albeit that it could and should be refined and improved, is an application which exists for any Pico to draw graphics on the host system. What do we have for displaying transferred core data ?

Return to “MicroPython”