Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #91983 > unrolled thread
| Started by | John McKenzie <davros@bellaliant.net> |
|---|---|
| First post | 2015-06-03 18:22 +0000 |
| Last post | 2015-08-16 19:45 +0000 |
| Articles | 20 on this page of 35 — 11 participants |
Back to article view | Back to comp.lang.python
Keypress Input John McKenzie <davros@bellaliant.net> - 2015-06-03 18:22 +0000
Re: Keypress Input Laura Creighton <lac@openend.se> - 2015-06-03 20:59 +0200
Re: Keypress Input Gary Herron <gherron@digipen.edu> - 2015-06-03 12:15 -0700
Re: Keypress Input Gary Herron <gherron@digipen.edu> - 2015-06-03 11:47 -0700
Re: Keypress Input Laura Creighton <lac@openend.se> - 2015-06-04 12:50 +0200
Re: Keypress Input John McKenzie <davros@bellaliant.net> - 2015-06-06 18:28 +0000
Re: Keypress Input Laura Creighton <lac@openend.se> - 2015-06-06 22:52 +0200
Re: Keypress Input Chris Angelico <rosuav@gmail.com> - 2015-06-07 07:20 +1000
Re: Keypress Input Michael Torrie <torriem@gmail.com> - 2015-06-06 22:31 -0600
Re: Keypress Input John McKenzie <davros@bellaliant.net> - 2015-06-15 05:15 +0000
Re: Keypress Input John McKenzie <davros@bellaliant.net> - 2015-06-16 15:09 +0000
Re: Keypress Input Christian Gollwitzer <auriocus@gmx.de> - 2015-06-19 07:20 +0200
Re: Keypress Input John McKenzie <davros@bellaliant.net> - 2015-06-20 14:59 +0000
Re: Keypress Input Rick Johnson <rantingrickjohnson@gmail.com> - 2015-07-15 18:03 -0700
Re: Keypress Input Michael Torrie <torriem@gmail.com> - 2015-07-15 22:30 -0600
Re: Keypress Input Rick Johnson <rantingrickjohnson@gmail.com> - 2015-07-16 10:22 -0700
Re: Keypress Input Michael Torrie <torriem@gmail.com> - 2015-07-16 15:27 -0600
Re: Keypress Input Terry Reedy <tjreedy@udel.edu> - 2015-07-16 02:08 -0400
Re: Keypress Input Rick Johnson <rantingrickjohnson@gmail.com> - 2015-07-16 11:30 -0700
Re: Keypress Input Terry Reedy <tjreedy@udel.edu> - 2015-07-16 03:10 -0400
Re: Keypress Input Michael Torrie <torriem@gmail.com> - 2015-07-16 15:29 -0600
Re: Keypress Input John McKenzie <davros@bellaliant.net> - 2015-06-15 05:23 +0000
Re: Keypress Input Oscar Benjamin <oscar.j.benjamin@gmail.com> - 2015-06-15 12:22 +0100
Re: Keypress Input Grant Edwards <invalid@invalid.invalid> - 2015-06-15 15:22 +0000
Re: Keypress Input Michael Torrie <torriem@gmail.com> - 2015-06-16 11:15 -0600
Re: Keypress Input John McKenzie <davros@bellaliant.net> - 2015-06-16 20:06 +0000
Re: Keypress Input Grant Edwards <invalid@invalid.invalid> - 2015-06-16 20:49 +0000
Re: Keypress Input Michael Torrie <torriem@gmail.com> - 2015-06-16 19:22 -0600
Re: Keypress Input Michael Torrie <torriem@gmail.com> - 2015-06-18 16:42 -0600
Re: Keypress Input John McKenzie <davros@bellaliant.net> - 2015-06-20 15:02 +0000
Re: Keypress Input Michael Torrie <torriem@gmail.com> - 2015-06-20 10:30 -0600
Re: Keypress Input Paul Rubin <no.email@nospam.invalid> - 2015-06-16 14:22 -0700
Re: Keypress Input John McKenzie <davros@bellaliant.net> - 2015-07-15 19:05 +0000
Re: Keypress Input Michael Torrie <torriem@gmail.com> - 2015-07-15 13:17 -0600
Re: Keypress Input John McKenzie <davros@bellaliant.net> - 2015-08-16 19:45 +0000
Page 1 of 2 [1] 2 Next page →
| From | John McKenzie <davros@bellaliant.net> |
|---|---|
| Date | 2015-06-03 18:22 +0000 |
| Subject | Keypress Input |
| Message-ID | <rBHbx.75089$MO7.40532@fx10.iad> |
Hello. Very new to Python and looking for some basic help. Would like a set-up where something happens when a key is pressed. Not propose a question, have the user type something, then hit return, then something happens, but just the R key is pressed, something happens, then something else happens if the B key is pressed, then a third thing happens if the G key is pressed. My research only served to confuse me. Firstly, I do not understand how it is possible for this to be a difficult thing not built into the system for any scripting language made within the last few decades. More to the point I am unclear on specific suggestions. Most of them seem to be for Windows only and I want this working on a Raspberry Pi. Saw getch but I am still confused if it is platform specific or not, or requires a module to be installed or not. Just get errors if I try to install getch using PIP. Other suggestions seemed to be overkill and confused me to due to my beginner level knowledge and the fact these suggestions have other, more complicated elements to them. I just want a button press on a device connected to a Raspberry Pi to trigger an action. If anyone can give me some guidance on this I would appreciate it. Thank you.
[toc] | [next] | [standalone]
| From | Laura Creighton <lac@openend.se> |
|---|---|
| Date | 2015-06-03 20:59 +0200 |
| Message-ID | <mailman.121.1433357959.13271.python-list@python.org> |
| In reply to | #91983 |
Tkinter runs on raspberry pi.
Get it installed, and then run this program.
from Tkinter import *
root = Tk()
prompt = 'Press any key. Remember to keep your mouse in the cyan box. '
lab = Label(root, text=prompt, width=len(prompt), bg='cyan')
lab.pack()
def key(event):
msg = 'event.char is %r and event.keysym is %r' % (event.char, event.keysym)
lab.config(text=msg)
root.bind_all('<Key>', key)
root.mainloop()
Now you will have to bind the various keys to do what it is you want.
You need to read online dociumentation for tkinter to learn how to do
this, as well as how to use tkinter in general.
Laura
[toc] | [prev] | [next] | [standalone]
| From | Gary Herron <gherron@digipen.edu> |
|---|---|
| Date | 2015-06-03 12:15 -0700 |
| Message-ID | <mailman.123.1433359762.13271.python-list@python.org> |
| In reply to | #91983 |
On 06/03/2015 11:22 AM, John McKenzie wrote:
> Hello.
>
> Very new to Python and looking for some basic help.
>
> Would like a set-up where something happens when a key is pressed. Not
> propose a question, have the user type something, then hit return, then
> something happens, but just the R key is pressed, something happens, then
> something else happens if the B key is pressed, then a third thing
> happens if the G key is pressed.
>
> My research only served to confuse me. Firstly, I do not understand how
> it is possible for this to be a difficult thing not built into the system
> for any scripting language made within the last few decades. More to the
> point I am unclear on specific suggestions. Most of them seem to be for
> Windows only and I want this working on a Raspberry Pi. Saw getch but I
> am still confused if it is platform specific or not, or requires a module
> to be installed or not. Just get errors if I try to install getch using
> PIP.
If you are using Python through a CLI (command line interface i.e., a
shell), then in fact your request doesn't really make sense. CLIs by
their nature don't support that kind of interaction.
BUT don't despair. Nearly every GIU framework on the planet has a
Python interface, and they all allow for a window to be opened with
event processing of your choice.
This are some good places to start:
https://wiki.python.org/moin/GuiProgramming
https://wiki.python.org/moin/GUI%20Programming%20in%20Python
Several of these (Tkinter and the curses module) are distributed with
Python, so you should already have them installed.
Gary Herron
>
> Other suggestions seemed to be overkill and confused me to due to my
> beginner level knowledge and the fact these suggestions have other, more
> complicated elements to them.
>
> I just want a button press on a device connected to a Raspberry Pi to
> trigger an action. If anyone can give me some guidance on this I would
> appreciate it.
>
> Thank you.
>
--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418
[toc] | [prev] | [next] | [standalone]
| From | Gary Herron <gherron@digipen.edu> |
|---|---|
| Date | 2015-06-03 11:47 -0700 |
| Message-ID | <mailman.122.1433359762.13271.python-list@python.org> |
| In reply to | #91983 |
On 06/03/2015 11:22 AM, John McKenzie wrote:
> Hello.
>
> Very new to Python and looking for some basic help.
>
> Would like a set-up where something happens when a key is pressed. Not
> propose a question, have the user type something, then hit return, then
> something happens, but just the R key is pressed, something happens, then
> something else happens if the B key is pressed, then a third thing
> happens if the G key is pressed.
>
> My research only served to confuse me. Firstly, I do not understand how
> it is possible for this to be a difficult thing not built into the system
> for any scripting language made within the last few decades. More to the
> point I am unclear on specific suggestions. Most of them seem to be for
> Windows only and I want this working on a Raspberry Pi. Saw getch but I
> am still confused if it is platform specific or not, or requires a module
> to be installed or not. Just get errors if I try to install getch using
> PIP.
If you are using Python through a CLI (command line interface i.e., a
shell), then in fact your request doesn't really make sense. CLIs by
their nature don't support that kind of interaction.
BUT don't despair. Nearly every GIU framework on the planet has a
Python interface, and they all allow for a window to be opened with
event processing of your choice.
This are some good places to start:
https://wiki.python.org/moin/GuiProgramming
https://wiki.python.org/moin/GUI%20Programming%20in%20Python
Several of these (Tkinter and the curses module) are distributed with
Python, so you should already have them installed.
Gary Herron
>
> Other suggestions seemed to be overkill and confused me to due to my
> beginner level knowledge and the fact these suggestions have other, more
> complicated elements to them.
>
> I just want a button press on a device connected to a Raspberry Pi to
> trigger an action. If anyone can give me some guidance on this I would
> appreciate it.
>
> Thank you.
>
--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418
[toc] | [prev] | [next] | [standalone]
| From | Laura Creighton <lac@openend.se> |
|---|---|
| Date | 2015-06-04 12:50 +0200 |
| Message-ID | <mailman.156.1433415061.13271.python-list@python.org> |
| In reply to | #91983 |
In a message of Wed, 03 Jun 2015 20:59:04 +0200, Laura Creighton writes:
>Tkinter runs on raspberry pi.
>
>Get it installed, and then run this program.
>
>from Tkinter import *
>root = Tk()
>prompt = 'Press any key. Remember to keep your mouse in the cyan box. '
>lab = Label(root, text=prompt, width=len(prompt), bg='cyan')
>lab.pack()
>
>def key(event):
> msg = 'event.char is %r and event.keysym is %r' % (event.char, event.keysym)
> lab.config(text=msg)
>
>root.bind_all('<Key>', key)
>root.mainloop()
>
>Now you will have to bind the various keys to do what it is you want.
>You need to read online dociumentation for tkinter to learn how to do
>this, as well as how to use tkinter in general.
>
>Laura
I was in a hurry last night. What I mean is -- Python out of the box
is not in the business of detecting key input. You normally use a
Gui kit for that. There are lots of them, and they all do things
sort of the same but slightly differently. So what you need is
a gui kit that runs on Raspberry Pi. If you are already using a
gui, then it probably will do it for you; check its documentation.
However, if you aren't using one ...
I don't have a Raspberry Pi, but I have read that tkinter runs there.
We can check. First make sure that tkinter is installed and run that
short program I posted (also included above). If it works -- every time
you press a key char, it is supposed to tell you what you typed -- then
you are in business. I just bound pressing every key with telling you that
it got pressed. You will need to bind particular keys to do particular
things, which you can read about in tkinter documentation about keybinding.
Tkinter is python wrapped around tk, so this page
http://www.tcl.tk/man/tcl8.6/TkCmd/keysyms.htm
lists all the keys you can bind. Not every OS provides the ability to
bind every key. You are advised to try the keys you want to bind with
Raspberry Pi -- not having one I cannot check this for you.
Laura
[toc] | [prev] | [next] | [standalone]
| From | John McKenzie <davros@bellaliant.net> |
|---|---|
| Date | 2015-06-06 18:28 +0000 |
| Message-ID | <hZGcx.45402$LN4.24632@fx02.iad> |
| In reply to | #91983 |
Laura and Gary, thank you for your replies. I have three physical buttons connected to a Kade device emulating a keyboard. These buttons control an LED light strip. So there is no screen, so a GUI did not cross my mind. I thought it made sense as it is easily done by other scripting languages. Thank you both for pointing my in the right direction. It turns out Tkinter is installed on Raspian and my Pi has it. Typing import tkinter into the Python interpreter gave me an error, then I corrected my spelling. The T should be upper case. No errors with "import Tkinter". Laura, thank you for typing up example code. I had to remove one indent on line 9, but after that it worked on my desktop. The Pi gave an error about Tkinter when I tried to run your code but I will work on that. In the meantime I will work my basic code out on the desktop and then move it over to the Pi, adapting it for and fixing Pi issues then. In my mind the Tkinter information I read on the web contradicts the examples given with the text, so obviously I am not getting it at all. Tkinter seems very confusing to me right now, but I think I just need to review the conceptual stuff again and keep trying. Also, I have your example, which I can experiment with. Thanks.
[toc] | [prev] | [next] | [standalone]
| From | Laura Creighton <lac@openend.se> |
|---|---|
| Date | 2015-06-06 22:52 +0200 |
| Message-ID | <mailman.220.1433623981.13271.python-list@python.org> |
| In reply to | #92187 |
In a message of Sat, 06 Jun 2015 18:28:29 +0000, John McKenzie writes: > > > Laura and Gary, thank you for your replies. I have three physical >buttons connected to a Kade device emulating a keyboard. These buttons >control an LED light strip. So there is no screen, so a GUI did not cross >my mind. I thought it made sense as it is easily done by other scripting >languages. Thank you both for pointing my in the right direction. > > It turns out Tkinter is installed on Raspian and my Pi has it. Typing >import tkinter into the Python interpreter gave me an error, then I >corrected my spelling. The T should be upper case. No errors with "import >Tkinter". > > Laura, thank you for typing up example code. I had to remove one indent >on line 9, but after that it worked on my desktop. The Pi gave an error >about Tkinter when I tried to run your code but I will work on that. In >the meantime I will work my basic code out on the desktop and then move >it over to the Pi, adapting it for and fixing Pi issues then. > > In my mind the Tkinter information I read on the web contradicts the >examples given with the text, so obviously I am not getting it at all. >Tkinter seems very confusing to me right now, but I think I just need to >review the conceptual stuff again and keep trying. Also, I have your >example, which I can experiment with. > > > Thanks. You are most welcome. Sorry if I mangled the indent when pasting it into my mail. http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html is useful. Especially http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/key-names.html So is http://effbot.org/tkinterbook/ Write back if you run into trouble. The simple code I sent is just about binding every key press to something that announces what you pressed. You will have to bind particular keys, or sequence of keys to what you want to do. Write a small example to make sure that tkinter can talk to your Kade device ok, because if it cannot we will have to look harder at the problem. Laura
[toc] | [prev] | [next] | [standalone]
| From | Chris Angelico <rosuav@gmail.com> |
|---|---|
| Date | 2015-06-07 07:20 +1000 |
| Message-ID | <mailman.221.1433625651.13271.python-list@python.org> |
| In reply to | #92187 |
On Sun, Jun 7, 2015 at 4:28 AM, John McKenzie <davros@bellaliant.net> wrote: > It turns out Tkinter is installed on Raspian and my Pi has it. Typing > import tkinter into the Python interpreter gave me an error, then I > corrected my spelling. The T should be upper case. No errors with "import > Tkinter". Ah, that means your Python interpreter is the older (version 2) type, rather than the newer (version 3). As of Python 3.0, the module is named "tkinter". Use whichever one you have; there are a few other changes inside the module, but the functionality's mostly the same. ChrisA
[toc] | [prev] | [next] | [standalone]
| From | Michael Torrie <torriem@gmail.com> |
|---|---|
| Date | 2015-06-06 22:31 -0600 |
| Message-ID | <mailman.227.1433651494.13271.python-list@python.org> |
| In reply to | #92187 |
On 06/06/2015 12:28 PM, John McKenzie wrote: > > Laura and Gary, thank you for your replies. I have three physical > buttons connected to a Kade device emulating a keyboard. These buttons > control an LED light strip. So there is no screen, so a GUI did not cross > my mind. I thought it made sense as it is easily done by other scripting > languages. Thank you both for pointing my in the right direction. I assume this is on a Linux box of some kind, perhaps an embedded computer? Actually you can indeed do what you want from a command-line program. The curses module supports a function called "getch" which grabs keys interactively from whatever tty or ptty you are running the program on. You'll have to consult the docs on curses and how to use it in this fashion. The problem is you can't just ssh into your device and run the program as it will fetch input from the terminal (and your remote keyboard) which isn't what you want. But if you can get it to run on the linux console, it would work. I have not idea how to do this in a non-interactive startup fashion. If your buttons are USB you might be able to read their status via libusb but that gets complicated as Linux tries to grab it as a HID keyboard.
[toc] | [prev] | [next] | [standalone]
| From | John McKenzie <davros@bellaliant.net> |
|---|---|
| Date | 2015-06-15 05:15 +0000 |
| Message-ID | <Tbtfx.178924$Jv.102633@fx26.iad> |
| In reply to | #91983 |
from Tkinter import *
from blinkstick import blinkstick
led = blinkstick.find_first()
timered = 0
timeyellow = 0
timeblue = 0
colour = None
root = Tk()
root.title('eFlag 1')
def red1(event):
colour = 1
def yellow1(event):
colour = 2
def blue1(event):
colour = 3
root.bind_all('r', red1)
root.bind_all('b', blue1)
root.bind_all('y', yellow1)
root.mainloop()
while colour == None:
led.pulse(red=0, green=255, blue=0, repeats=1, duration=5000,
steps=50)
while colour == 1:
led.pulse(red=255, green=0, blue=0, repeats=1, duration=3000,
steps=50)
timered += 1
while colour == 2:
led.pulse(red=255, green=255, blue=0, repeats=1, duration=3000,
steps=50)
timeyellow += 1
while colour == 3:
led.pulse(red=0, green=0, blue=255, repeats=1, duration=2000,
steps=50)
timeblue += 1
def exit_handler():
print '\033[0;41;37mRed Team:\033[0m ', timered
print '\033[0;43;30mYellow Time:\033[0m ', timeyellow
print '\033[0;44;37mBlue Time:\033[0m ', timeblue
flog = open('flag1log.text', 'a')
flog.write(timestamp + '\n' + 'Red Team: ' + str(timered) + '\n' +
'Yellow Team: ' + str(timeyellow) + '\n' + 'Blue Team: ' + str(timeblue)
+ '\n')
flog.close()
atexit.register(exit_handler)
[toc] | [prev] | [next] | [standalone]
| From | John McKenzie <davros@bellaliant.net> |
|---|---|
| Date | 2015-06-16 15:09 +0000 |
| Message-ID | <4%Wfx.125346$HH2.100763@fx20.iad> |
| In reply to | #92621 |
It appears that one of my posts was cut off. It contains my script but none of the lengthy text in front of it. To summarize, my set-up consists of three "massive arcade buttons" from Adafruit. one red, one blue, one yellow. They are connected to a Kade Device that is connected to a Raspberry Pi via USB cable and emulates a USB keyboard. The goal is to get the LED light strip attached to the Pi via a Blinkstick Pro and LED adapter to glow the colour of the button pushed. Also, I want the Pi to record how long it spent as each colour. For development purposes I am using an actual keyboard. The script brings up a blank tkinker window (expected) and the window seems to have focus when it is created. Pressing the keys does nothing. Would appreciate any insight into why it does not respond. Just look a few posts above (Date: Mon, 15 Jun 2015 05:15:31 GMT) and you will see my script. Tried a bunch of different approaches and in some of them, an error message appeared when I pressed a key. It may not have worked, but it was registering the key press. Thanks.
[toc] | [prev] | [next] | [standalone]
| From | Christian Gollwitzer <auriocus@gmx.de> |
|---|---|
| Date | 2015-06-19 07:20 +0200 |
| Message-ID | <mm08nk$caf$1@dont-email.me> |
| In reply to | #92621 |
Am 15.06.15 um 07:15 schrieb John McKenzie:
>
> from Tkinter import *
> from blinkstick import blinkstick
>
> led = blinkstick.find_first()
>
> timered = 0
> timeyellow = 0
> timeblue = 0
>
> colour = None
>
> root = Tk()
> root.title('eFlag 1')
>
>
>
> def red1(event):
> colour = 1
>
> def yellow1(event):
> colour = 2
>
> def blue1(event):
> colour = 3
>
> root.bind_all('r', red1)
> root.bind_all('b', blue1)
> root.bind_all('y', yellow1)
The nonsense starts here:
===================
> root.mainloop()
>
> while colour == None:
> led.pulse(red=0, green=255, blue=0, repeats=1, duration=5000,
> steps=50)
>
> while colour == 1:
> led.pulse(red=255, green=0, blue=0, repeats=1, duration=3000,
> steps=50)
> timered += 1
>
> while colour == 2:
> led.pulse(red=255, green=255, blue=0, repeats=1, duration=3000,
> steps=50)
> timeyellow += 1
>
> while colour == 3:
> led.pulse(red=0, green=0, blue=255, repeats=1, duration=2000,
> steps=50)
> timeblue += 1
====================
it seems you don't understand event based programming. root.mainloop()
never exits. It waits for the user input and does the dispatching, i.e.
when a key is pressed, then according to your bindings, the functions
red1, yellow1, blue1 are called, which set a variable but do not do
nything else. To see that, just insert a print statement into these
functions:
def red1(event):
colour = 1
print("Red ws called")
Now your job is to also do the functionality there, i.e. you have to
reformulate your task (waiting for red, then blue...) as a state
machine. Alternatively you can circumvent to redo the logic in a state
machine by using a coroutine.
You should read a text about GUI programming, or more specifically event
based programming, to understand your mistake.
Christian
>
> def exit_handler():
> print '\033[0;41;37mRed Team:\033[0m ', timered
> print '\033[0;43;30mYellow Time:\033[0m ', timeyellow
> print '\033[0;44;37mBlue Time:\033[0m ', timeblue
> flog = open('flag1log.text', 'a')
> flog.write(timestamp + '\n' + 'Red Team: ' + str(timered) + '\n' +
> 'Yellow Team: ' + str(timeyellow) + '\n' + 'Blue Team: ' + str(timeblue)
> + '\n')
> flog.close()
> atexit.register(exit_handler)
>
>
[toc] | [prev] | [next] | [standalone]
| From | John McKenzie <davros@bellaliant.net> |
|---|---|
| Date | 2015-06-20 14:59 +0000 |
| Message-ID | <ldfhx.15511$C_.5118@fx15.iad> |
| In reply to | #92871 |
Christian, are you suggesting I learn to do everything perfectly before I ask how to do everything perfectly? Despite your tone and insults I honestly appreciate the response. I know what to focus on and less than 5 minutes from now I will be looking for e- books on the specific subjects you point me to and will have a better idea of where the issues are.
[toc] | [prev] | [next] | [standalone]
| From | Rick Johnson <rantingrickjohnson@gmail.com> |
|---|---|
| Date | 2015-07-15 18:03 -0700 |
| Message-ID | <3fec5a1e-44e6-4e3c-ab01-2703f2911c50@googlegroups.com> |
| In reply to | #92871 |
On Friday, June 19, 2015 at 12:20:14 AM UTC-5, Christian Gollwitzer wrote:
> The nonsense starts here:
>
> [...snip code...]
>
> it seems you don't understand event based programming.
Duh. No need to abuse the lad.
> It waits for the user input and does the dispatching, i.e.
> when a key is pressed, then according to your bindings,
> the functions red1, yellow1, blue1 are called, which set a
> variable but do not do nything else.
>
> Now your job is to also do the functionality there, i.e.
> you have to reformulate your task (waiting for red, then
> blue...) as a state machine. Alternatively you can
> circumvent to redo the logic in a state machine by using a
> coroutine.
State machines? Co-routines? Dispatching? Bindings? Are you
purposefully attempting to scare the OP away from GUI
programming forever, or merely practicing for your next tenure
exam? Heck you're scaring me away and i have years of GUI
programming experience under my belt!
> You should read a text about GUI programming, or more
> specifically event based programming, to understand your
> mistake.
Christian, peppering a student with a barrage of technical
verbiage and then smacking them in the face with that tried
and true knee-jerk-reactionary condescension of RTFM, is
hardly the reaction that the OP deserves when he *DID*
attempt to formulate working code from the sample that Laura
provided. And even *IF* his attempt was an abysmal failure, we
should strive to provide more information than simply: "go
study the history of GUI design and get back to us in a year
or two". Of course, we don't want to write the code for him,
but his attempt does warrant a few extra clues.
============================================================
@ John
============================================================
You may have solved your input capturing problem, and i
don't think a GUI is the preferred solution for a
graphically deficient device anyhow, but you may well need a
GUI in the future, and this would be a fine example from which
to learn.
So you want to know about Event Driven Programming do ya?
Well then, skip the boring lectures and the hours of eyeball
parsing techno-babble-prose and listen up!
You see, we, as humans, emulate a version of Event Driven
Programming (or EDP) in our everyday lives as something i
shall henceforth refer to as Event Driven Reactions (or
EDR). And these EDRs are codified as culturally acceptable
reactions to external stimuli during the course of
interpersonal relations.
For instance:
If we meet someone for the first time and they extend
their hand, then we should extend ours and engage in the
"hand shake" or the "fist bump" (depending upon cultural
norms). And if you're in one of those really freaky cultures
you may have to kiss someone... YUCK!
Or if someone insults us with a sexual advance, and we're
of the female persuasion, and they're of the male
persuasion: then we might react (as "Manolo" found out in
that famous scene from "Scarface") by slapping them *SMACK*
The point is: The action of us reacting to external stimuli
(based on predefined rules) is the exact nature of Event
Driven GUIs. When we write GUI code under this paradigm, we
need to follow a few design rules.
(1) DEFINE/CREATE THE REQUIRED GUI COMPONENTS
Here we define the window(s) and the required widgets that
shall provide an interface between our users and our code.
(2) DEFINE RULES FOR REACTIONS TO EXTERNAL STIMULI
Here we bind events (keyboard, mouse, joystick, etc) to
callbacks (aka: functions in Python) that our "master
control program" (aka: Tkinter in this instance) will
execute when the defined event is recieved.
Now you may be asking yourself: "But i did that already! Why
does my code fail to produce required results?"
Hmm, it seems (as Christian pointed out) you made the fatal
flaw of starting the event loop before your logic could
execute. However. Even if your logic was allowed to execute,
it would fail to produce the desired results.
============================================================
THE ROAD TO ENLIGHTENMENT:
============================================================
I have re-packaged Laura's basic example into a class format
that utilizes a paradigm known as Object Oriented
Programming (or OOP). Of course, you're not required to
write code utilizing this format, but i feel it may be
easier for a GUI novice to understand the entire structure
of this program when the relevant bits are in near proximity
to one another, rather than spread around a module like a
spilled carton of toothpicks on the floor -- because, not
all of us are blessed with the narrowly focused genius of
the "idiot savant"!
Now, conceptualize the entire class as representing the window
whilst it's "alive", and the methods defined in the class as
"personal reactions" to events that the window encounters
during it's lifetime. You should think of the window as a
unique object in two dimensional space, just as you and i
are unique objects in three dimensional space.
Furthermore, looking over the code you should recognize two
distinct "syntactical groupings"
(1) The "App object"
(2) The instantiation of the that App object
(psst: look below __name__ == '__main__')
The object and the instantation of the object are now
clearly defined by utilizing a "naturally linear" syntactical
progression.
Moreover, the functional behavior of the object is defined
from *INSIDE* the object and *NOT* in the next room or next
solar system. Most humans find this format to be a more
natural way of writing code as it mirrors the conceptual
observation of real life systems, objects, and the encapsulation
of their innate behaviors. Enjoy.
## BEGIN "AWESOME CODE" ##
import Tkinter as tk
from tkMessageBox import showinfo, showerror
MSG1 = """\
To begin retinal stimulation, press r or g or b on your keyboard
Hold key down for extended stimulation!
"""
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.bind("<KeyPress>", self.evtKeyDown)
self.bind("<KeyRelease>", self.evtKeyUp)
self.protocol("WM_DELETE_WINDOW", self.evtDeleteWindow)
w = tk.Label(self, text=MSG1)
w.pack()
self.config(bg='white')
self.geometry('500x500')
self.focus_set()
def evtDeleteWindow(self):
showinfo("The window is Dying", "Goodbye cruel world!", parent=self)
self.destroy()
def evtKeyDown(self, event):
key = event.keysym.lower()
alert = False
if key == 'r':
self.config(bg='red')
elif key == 'g':
self.config(bg='green')
elif key == 'b':
self.config(bg='blue')
else:
msg = 'I *TOLD* you to press r or g or b, not {0!r}!'.format(key)
showerror('', msg, parent=self)
def evtKeyUp(self, event):
self.config(bg='white')
if __name__ == '__main__':
app = App()
app.title('Retina Stimultor')
app.mainloop()
print "This code only executes *AFTER* the mainloop call returns!"
## END "AWESOME CODE" ##
PS: Don't be too upset at Christian. He's probably just
grumpy due to the excessive trolling and emotional warfare
that plagues this fine group. I'm sure he did not mean to
offend. Of course it could be that he's having withdraw
systems due to my extended absence. Who knows? Perhaps if i
found this group to more intellectually stimulating i might
be inclined to participate on a regular basis.
[toc] | [prev] | [next] | [standalone]
| From | Michael Torrie <torriem@gmail.com> |
|---|---|
| Date | 2015-07-15 22:30 -0600 |
| Message-ID | <mailman.555.1437021019.3674.python-list@python.org> |
| In reply to | #93888 |
On 07/15/2015 07:03 PM, Rick Johnson wrote: > <too much to quote> I think you've missed the whole point of the OP's project. He doesn't want to make a GUI. He simply wants to have his program do something like blink an LED when someone presses a big red button. He just wanted a quick way to test things out since his big red button can emulate a USB keyboard. So all he needed was a simple console app that can fetch keystrokes. In the end, though GPIO is very simple both electrically and in terms of Python, so that is the ultimate route he will go. If you read his last post you'll find he says this.
[toc] | [prev] | [next] | [standalone]
| From | Rick Johnson <rantingrickjohnson@gmail.com> |
|---|---|
| Date | 2015-07-16 10:22 -0700 |
| Message-ID | <92d31684-8003-4b9e-9f2a-925a421d05c6@googlegroups.com> |
| In reply to | #93895 |
On Wednesday, July 15, 2015 at 11:30:40 PM UTC-5, Michael Torrie wrote:
> On 07/15/2015 07:03 PM, Rick Johnson wrote:
> > <too much to quote>
>
> I think you've missed the whole point of the OP's project.
Obviously my reply was not only "too much to quote", but
apparently, and sadly, "too much to read"! I don't know about
anyone else here, but i would be cautious about replying to
any post before i took the time to read the entire content. I
mean, i'd wouldn't want to embarrass myself.
But, I suppose this more evidence of the damage social media
is doing to our collective attention spans. There are some
studies that report an average attention span of only 8
seconds -- which is less than the attention span of a
goldfish. AN EFFING GOLDFISH!
CLOWN-FISH: Hello Dori!
DORI: Who's Dori?
I had read an article the other day about how "smart phones
are making people dumb". However, by focusing on the phone,
which is nothing more than a tool, the author ignored the
real cause of this ubiquitous intelligence drain that is
rotting our culture from the inside out.
It's not the *PHONES* that making people dumb, it's the
*CONTENT* people *CHOOSE* that is turning us into a society
of drooling, superficial, and mindless gossip zombies.
TWITTER BEING THE MOST DESTRUCTIVE AND EVIL OF THEM ALL!
With Twitter, we have a communication medium that encourages
teeny tiny thoughtless reactions to whatever "emotional
drivel" happens to be churning around in the daily cesspools
of what, for whatever "sociological reason", we still refer
to as "News".
Is the size of some morally corrupt celeb's butt really
"news"? Or the love interest of various talent-less
glitterati anything we should concern ourselves with? Heck,
just a few days ago, another "lip singer" made
front page world news simply by licking a donut! BY LICKING
AN EFFING DONUT! Are our lives that pathetic?
In the past there were at least a few educational programs
on the tele, now even so called "educational channels" have
devolved into train-wrecks of thought UNprovoking emotion,
with episode after episode of "totally scripted reality TV"
far more concerned with shock value than entertainment --
much less "education".
I once believed that Facebook was the "bottom of the barrel"
for social media -- BOY WAS I WRONG! It's seems there is no
level that we, as a society will stoop, in the effort to
destroy our capacity of intellectual evolution. So fire up
those twitter engines and speed headlong into that wall of
ignorant bliss!
And don't bother trotting out the old cliche of "grab a
fiddle" folks, because the unwashed masses are not refined
enough to appreciate the "higher intellectual emotions" and
the thoughtful introspection that such an instrument can
produce, instead, grab a shiny rattle and shake it in front
of their pasty little ignorant faces. For they can only
understand simple concepts and the selfish emotions.
>:-O =
=
=
___^ __ ^_____
___'Modern-Society'___
[toc] | [prev] | [next] | [standalone]
| From | Michael Torrie <torriem@gmail.com> |
|---|---|
| Date | 2015-07-16 15:27 -0600 |
| Message-ID | <mailman.613.1437082090.3674.python-list@python.org> |
| In reply to | #93939 |
On 07/16/2015 11:22 AM, Rick Johnson wrote: > On Wednesday, July 15, 2015 at 11:30:40 PM UTC-5, Michael Torrie wrote: >> On 07/15/2015 07:03 PM, Rick Johnson wrote: >>> <too much to quote> >> >> I think you've missed the whole point of the OP's project. > > Obviously my reply was not only "too much to quote", but > apparently, and sadly, "too much to read"! I don't know about > anyone else here, but i would be cautious about replying to > any post before i took the time to read the entire content. I > mean, i'd wouldn't want to embarrass myself. I read a good deal of what you wrote, which is more than most do with such long, rambling posts. Good to know there were some good nuggets in there. This is as much as I read of your current post though. As soon as you started going off about gold fish, I'm out. It's true that attention spans are shorter these days. But it's also true there are ways of being concise.
[toc] | [prev] | [next] | [standalone]
| From | Terry Reedy <tjreedy@udel.edu> |
|---|---|
| Date | 2015-07-16 02:08 -0400 |
| Message-ID | <mailman.559.1437026959.3674.python-list@python.org> |
| In reply to | #93888 |
On 7/15/2015 9:03 PM, Rick Johnson wrote:
> You may have solved your input capturing problem, and i
> don't think a GUI is the preferred solution for a
> graphically deficient device anyhow, but you may well need a
> GUI in the future, and this would be a fine example from which
> to learn.
This really is a nice example. Your rationale for defining an app class
is the best I remember seeing.
To run in 3.x, change the first two lines to
import tkinter as tk
from tkinter.messagebox import showinfo, showerror
> import Tkinter as tk
> from tkMessageBox import showinfo, showerror
>
> MSG1 = """\
> To begin retinal stimulation, press r or g or b on your keyboard
> Hold key down for extended stimulation!
> """
>
> class App(tk.Tk):
> def __init__(self):
> tk.Tk.__init__(self)
> self.bind("<KeyPress>", self.evtKeyDown)
> self.bind("<KeyRelease>", self.evtKeyUp)
> self.protocol("WM_DELETE_WINDOW", self.evtDeleteWindow)
> w = tk.Label(self, text=MSG1)
> w.pack()
> self.config(bg='white')
> self.geometry('500x500')
> self.focus_set()
>
> def evtDeleteWindow(self):
> showinfo("The window is Dying", "Goodbye cruel world!", parent=self)
> self.destroy()
>
> def evtKeyDown(self, event):
> key = event.keysym.lower()
> alert = False
> if key == 'r':
> self.config(bg='red')
> elif key == 'g':
> self.config(bg='green')
> elif key == 'b':
> self.config(bg='blue')
> else:
Can condense block above to this easily extended code: (Replacing if
if/elif/elif/... chains, when possible, is part of mastering Python.)
try:
self['bg'] = {'r':'red', 'g':'green', 'b':'blue'}[key]
except KeyError:
> msg = 'I *TOLD* you to press r or g or b, not {0!r}!'.format(key)
> showerror('', msg, parent=self)
>
> def evtKeyUp(self, event):
> self.config(bg='white')
>
> if __name__ == '__main__':
> app = App()
> app.title('Retina Stimultor')
> app.mainloop()
> print "This code only executes *AFTER* the mainloop call returns!"
Adding parens to print, when there is a single object being printed, has
no effect in 2.x and makes the statement work in 3.x. The following
works the same in both.
print("Mainloop has returned")
--
Terry Jan Reedy
[toc] | [prev] | [next] | [standalone]
| From | Rick Johnson <rantingrickjohnson@gmail.com> |
|---|---|
| Date | 2015-07-16 11:30 -0700 |
| Message-ID | <6d0248bd-415d-4801-bfde-acab06317da7@googlegroups.com> |
| In reply to | #93899 |
On Thursday, July 16, 2015 at 1:09:32 AM UTC-5, Terry Reedy wrote:
> This really is a nice example. Your rationale for defining an app class
> is the best I remember seeing.
Well thank you Terry. Your many years of selfless altruistic
offerings to this fine group are both inspiring and
educational. And i can happily admit that you are no doubt
much more of an asset to this group than i.
> > def evtKeyDown(self, event):
> > key = event.keysym.lower()
> > alert = False
Oops. I just noticed that i forgot to remove the "alert =
False" line. It was an artifact from one of my earlier
versions. It's obviously superfluous to we pyhtonistas, but
it could become a source of confusion to the shadow lurkers.
> > if key == 'r':
> > self.config(bg='red')
> > elif key == 'g':
> > self.config(bg='green')
> > elif key == 'b':
> > self.config(bg='blue')
> > else:
>
> Can condense block above to this easily extended code: (Replacing if
> if/elif/elif/... chains, when possible, is part of mastering Python.)
>
> try:
> self['bg'] = {'r':'red', 'g':'green', 'b':'blue'}[key]
> except KeyError:
Yes you make a good point. And i'm glad you injected this
alternative, as it offers yet another fine "teaching moment"
for the OP and this group.
[Warning: Caveat ahead!]
However, i must take exception with your claim that
replacing "classical conditional chains" with Python's
unofficial "pseudo case/switch" is key to: "mastering
Python". I feel there are instances when a "classical
condition chain" are more appropriate, and then other times,
when the "pseudo switch/case" is superior.
For me, I believe the "key to mastering Python" is not to
choose one method over the other (as some sort of religious
rule carved into stone), rather, to know when one method is more
appropriate than the other. That's my person opinion anyway.
> Adding parens to print, when there is a single object
> being printed, has no effect in 2.x and makes the
> statement work in 3.x. The following works the same in
> both.
>
> print("Mainloop has returned")
Yes, another fine teaching moment! But just to be clear of
my intentions: I only write code in full 2.x compliance, or
full 3.x compliance. And i do this because i don't want to
inject any "implicit version confusion" into my source code.
In fact, the only time i will mix the incompatible syntaxes
is when i can wrap them explicitly in an exception handler.
But since there is no exception to catch in this case, even
that option would be unavailable to me.
But again. The act of you pointing out this easily
overlooked difference between print 2.x and print(3.x) is
yet another opportunity at exploiting fundamental teaching
moments as they pop up. Hey, who would ever have "thunk" that
teaching could be as exciting and egotistically
fulfilling as a game of wack-a-mole! O:-)
[toc] | [prev] | [next] | [standalone]
| From | Terry Reedy <tjreedy@udel.edu> |
|---|---|
| Date | 2015-07-16 03:10 -0400 |
| Message-ID | <mailman.566.1437030654.3674.python-list@python.org> |
| In reply to | #93888 |
On 7/16/2015 12:30 AM, Michael Torrie wrote: > On 07/15/2015 07:03 PM, Rick Johnson wrote: >> <too much to quote> > > I think you've missed the whole point of the OP's project. He doesn't > want to make a GUI. He simply wants to have his program do something > like blink an LED when someone presses a big red button. He just wanted > a quick way to test things out since his big red button can emulate a > USB keyboard. So all he needed was a simple console app that can fetch > keystrokes. In the end, though GPIO is very simple both electrically > and in terms of Python, so that is the ultimate route he will go. If > you read his last post you'll find he says this. Rick pretty much acknowledged what you said in this paragraph. "You may have solved your input capturing problem, and i don't think a GUI is the preferred solution for a graphically deficient device anyhow, but you may well need a GUI in the future, and this would be a fine example from which to learn." It is a fine example. -- Terry Jan Reedy
[toc] | [prev] | [next] | [standalone]
Page 1 of 2 [1] 2 Next page →
Back to top | Article view | comp.lang.python
csiph-web