473,498 Members | 1,938 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Tkinter.Button subclass needs tuple constructor argument

TMS
119 New Member
OK, suppose there is a tuple of tuples like this:

Expand|Select|Wrap|Line Numbers
  1. s = (('a\nb', 1), ('c\nd', 1), ('e\nf', 1), 
  2. ('g\nh', 1), ('i\nj', 1), ('k\nl', 1))
  3.  
and I want each tuple to be on one widget and 1st three is on top row, 2nd 3 is on 2nd row. How would I iterate through this? I've tried some stuff, but nothing is making sense.

tms
Mar 13 '07 #1
30 1863
bartonc
6,596 Recognized Expert Expert
OK, suppose there is a tuple of tuples like this:

Expand|Select|Wrap|Line Numbers
  1. s = (('a\nb', 1), ('c\nd', 1), ('e\nf', 1), 
  2. ('g\nh', 1), ('i\nj', 1), ('k\nl', 1))
  3.  
and I want each tuple to be on one widget and 1st three is on top row, 2nd 3 is on 2nd row. How would I iterate through this? I've tried some stuff, but nothing is making sense.

tms
Sorry TMS, I'm not sure if you're using Tkinter or something else. Do you want to create Entry widgets (not usually multiline) or Text widgets?
Mar 13 '07 #2
TMS
119 New Member
buttons, they need to be buttons that respond and will print what the value of the button says based on a state. So, when in a state 1 the second line prints, in state 2 the 1st line prints within each button. I hope that is clearer.

:)

tms
Mar 13 '07 #3
TMS
119 New Member
OH, and I'm using Tkinter...think typewriter.
Mar 13 '07 #4
bartonc
6,596 Recognized Expert Expert
OH, and I'm using Tkinter...think typewriter.
Here's the way I see it; tested for one button only. Let's see if you can loop and create a grid. There's help here if you get stuck.
Expand|Select|Wrap|Line Numbers
  1. from Tkinter import *
  2.  
  3.  
  4. buttonData = (('a\nb', 1), ('c\nd', 1), ('e\nf', 1),
  5.               ('g\nh', 1), ('i\nj', 1), ('k\nl', 1))
  6. nColumns = 3
  7. nRows = len(buttonData)/nColumns
  8.  
  9.  
  10. class KeyButton(Button):
  11.     def __init__(self, parent, label, state):
  12.         self.btnStates = label.split()
  13.         self.state = state
  14.         Button.__init__(self, parent, text=label, command=self.DoAction)
  15.  
  16.     def DoAction(self):
  17.         try:
  18.             print self.btnStates[self.state]
  19.         except IndexError:
  20.             print "No such state"
  21.  
  22.     def SetState(self, state):
  23.         self.state = state
  24.  
  25.  
  26.  
  27.  
  28. if __name__ == "__main__":
  29.     root = Tk()
  30.     keyButton = KeyButton(root, buttonData[0][0], buttonData[0][1])
  31.     keyButton.grid(row=0, column=0)
  32.     root.mainloop()
  33.  
Mar 13 '07 #5
bartonc
6,596 Recognized Expert Expert
buttons, they need to be buttons that respond and will print what the value of the button says based on a state. So, when in a state 1 the second line prints, in state 2 the 1st line prints within each button. I hope that is clearer.

:)

tms
After I changed the title of the thread, I liked this way a little better:
Expand|Select|Wrap|Line Numbers
  1. from Tkinter import *
  2.  
  3.  
  4. buttonData = (('a\nb', 1), ('c\nd', 1), ('e\nf', 1),
  5.               ('g\nh', 1), ('i\nj', 1), ('k\nl', 1))
  6. nColumns = 3
  7. nRows = len(buttonData)/nColumns
  8.  
  9.  
  10. class KeyButton(Button):
  11.     def __init__(self, parent, label_state):
  12.         label = label_state[0]
  13.         self.btnStates = label.split()
  14.         self.state = label_state[1]
  15.         Button.__init__(self, parent, text=label, command=self.DoAction)
  16.  
  17.     def DoAction(self):
  18.         try:
  19.             print self.btnStates[self.state]
  20.         except IndexError:
  21.             print "No such state"
  22.  
  23.     def SetState(self, state):
  24.         self.state = state
  25.  
  26.  
  27.  
  28.  
  29. if __name__ == "__main__":
  30.     root = Tk()
  31.     keyButton = KeyButton(root, buttonData[0])
  32.     keyButton.grid(row=0, column=0)
  33.     root.mainloop()
  34.  
Mar 13 '07 #6
bartonc
6,596 Recognized Expert Expert
OK, suppose there is a tuple of tuples like this:

Expand|Select|Wrap|Line Numbers
  1. s = (('a\nb', 1), ('c\nd', 1), ('e\nf', 1), 
  2. ('g\nh', 1), ('i\nj', 1), ('k\nl', 1))
  3.  
and I want each tuple to be on one widget and 1st three is on top row, 2nd 3 is on 2nd row. How would I iterate through this? I've tried some stuff, but nothing is making sense.

tms
Hint: append to a list of Buttons as you create each button. Then you can:
Expand|Select|Wrap|Line Numbers
  1. btnList[i].SetState(0)  # or 1
in a loop or individually.
Mar 13 '07 #7
bartonc
6,596 Recognized Expert Expert
buttons, they need to be buttons that respond and will print what the value of the button says based on a state. So, when in a state 1 the second line prints, in state 2 the 1st line prints within each button. I hope that is clearer.

:)

tms
Yeah... It's gonna be a lot easier if your numbering system is always "zero based". That way in state 0 you print the 0th item, etc. There are ways (subtract from the state before using it as an index or empty 0th slots) but you'll regret using them in a very short time.
Mar 13 '07 #8
TMS
119 New Member
Wow... thanks thats great. It was the iterating through the tuples that I'm having a problem with, but your answer is very helpful for the next steps.

I'm sure its become apparant that I'm trying to write a virtual keyboard. The layout I was given is a tuple with tuples. I can't seem to get the layout to work with any iteration process I've tried.

The first row is the first tuple... like I gave in the example. Then the second tuple is the second row... like that. I am supposing the number given is the padding needed because in the layout I was given it gives this for backspace: ('Backspace', 2). I'm sure I can figure that part out... I just need to get the iteration so get the keyboard to layout correctly. Should be easy after learning Python in a month and a 1/2 right?


tms
Mar 13 '07 #9
bartonc
6,596 Recognized Expert Expert
Wow... thanks thats great. It was the iterating through the tuples that I'm having a problem with, but your answer is very helpful for the next steps.

I'm sure its become apparant that I'm trying to write a virtual keyboard. The layout I was given is a tuple with tuples. I can't seem to get the layout to work with any iteration process I've tried.
I copied, renamed and reformatted your example:
Expand|Select|Wrap|Line Numbers
  1. buttonData = (('a\nb', 1), ('c\nd', 1), ('e\nf', 1),
  2.               ('g\nh', 1), ('i\nj', 1), ('k\nl', 1))
It is indeed a tuple of tuples.
The first row is the first tuple... like I gave in the example. Then the second tuple is the second row... like that.
Would look more like
Expand|Select|Wrap|Line Numbers
  1. buttonData = ((('a\nb', 1), ('c\nd', 1), ('e\nf', 1)),
  2.               (('g\nh', 1), ('i\nj', 1), ('k\nl', 1)))
I am supposing the number given is the padding needed because in the layout I was given it gives this for backspace: ('Backspace', 2).
That makes a lot of sense to me.
I'm sure I can figure that part out... I just need to get the iteration so get the keyboard to layout correctly. Should be easy after learning Python in a month and a 1/2 right?


tms
Well easy for some after twice that long (maybe)! Keep it up!
Mar 13 '07 #10
TMS
119 New Member
But see that's the problem. How do I iterate through and perhaps map the tuple to the button?

[font=Verdana][size=2][/size][/font]
Mar 13 '07 #11
bartonc
6,596 Recognized Expert Expert
But see that's the problem. How do I iterate through and perhaps map the tuple to the button?

[font=Verdana][size=2][/size][/font]
Expand|Select|Wrap|Line Numbers
  1. for rowNum, rowTuple in enumerate(buttonData):
  2.     for colNum, constTuple in enumerate(rowTuple):
  3.         # here you have everything you need to create KeyButtons in a grid.
  4.         print rowNum, colNum, constTuple
enumerate() maps index, listortuple[index] pairs for you.
Mar 13 '07 #12
TMS
119 New Member
OK, making progress. I get an empty frame, so I'm haven't formated the loop correctly. Here it is:

Expand|Select|Wrap|Line Numbers
  1. for rowNum, rowTuple in enumerate(buttonData):
  2.             for colNum, constTuple in enumerate(rowTuple):
  3.                 keyButton=KeyButton(root, buttonData[rowTuple])  #I put this in...
  4. keyButton.grid(row=0, column=0)
  5. nColumns = 3
  6. nRows = len(buttonData)/nColumns
  7.  
so... once again, help..... please.....

(I honestly wish I didn't take this class, its been so frustrating to learn so quickly! I'm enjoying the language, but wish it was so much slower).
Mar 13 '07 #13
bartonc
6,596 Recognized Expert Expert
OK, making progress. I get an empty frame, so I'm haven't formated the loop correctly. Here it is:

Expand|Select|Wrap|Line Numbers
  1. for rowNum, rowTuple in enumerate(buttonData):
  2.             for colNum, constTuple in enumerate(rowTuple):
  3.                 keyButton=KeyButton(root, buttonData[rowTuple])  #I put this in...
  4. keyButton.grid(row=0, column=0)
  5. nColumns = 3
  6. nRows = len(buttonData)/nColumns
  7.  
so... once again, help..... please.....

(I honestly wish I didn't take this class, its been so frustrating to learn so quickly! I'm enjoying the language, but wish it was so much slower).
You were so close! I took the liberty of adding the list so that you can access each button. I haven't tested this, so let me know if there's any problem.
Expand|Select|Wrap|Line Numbers
  1. btnList = []  # an empty list
  2. for rowNum, rowTuple in enumerate(buttonData):
  3.     for colNum, constTuple in enumerate(rowTuple):
  4.         keyButton=KeyButton(root, buttonData[constTuple])  #I put this in... NEED INNER MOST DATA!
  5.         keyButton.grid(row=rowNum, column=colNum)
  6.         btnList.append(keyButton)  # a linerar list of all the buttons.
  7.  
  8.  
Mar 14 '07 #14
TMS
119 New Member
still getting an empty frame. Here is the exact code I'm using, including the layout for the keyboard.

Expand|Select|Wrap|Line Numbers
  1. from Tkinter import *
  2. buttonData = (
  3.     ( ('~\n`', 1), ('!\n1', 1), ('@\n2', 1), ('#\n3', 1), ('$\n4', 1),
  4.      ('%\n5', 1), ('^\n6', 1), ('&\n7', 1), ('*\n8', 1), ('(\n9', 1),
  5.      (')\n0', 1), ('_\n-', 1), ('+\n=', 1), ('Backspace', 2),
  6.      ),
  7.     ( ('Tab', 2), ('Q', 1), ('W', 1), ('E', 1), ('R', 1), ('T', 1),
  8.      ('Y', 1), ('U', 1), ('I', 1), ('O', 1), ('P', 1), ('{\n[', 1),
  9.      ('}\n]', 1), ('|\n\\', 1)
  10.      ),
  11.     ( ('CapsLock', 2), ('A', 1), ('S', 1), ('D', 1), ('F', 1), ('G', 1),
  12.      ('H', 1), ('J', 1), ('K', 1), ('L', 1), (':\n;', 1), ('"\n\'', 1),
  13.      ('Enter', 2)
  14.      ),
  15.     ( ('Shift', 2), ('Z', 1), ('X', 1), ('C', 1), ('V', 1), ('B', 1),
  16.      ('N', 1), ('M', 1), ('<\n,', 1), ('>\n.', 1), ('?\n/', 1), ('Shift', 3),
  17.      ),
  18.     ( ('Ctrl', 2), ('Alt', 2), ('Space', 7), ('Alt', 2), ('Ctrl', 2),
  19.      ),
  20.     )
  21.  
  22.  
  23. class KeyButton(Button):
  24.     def __init__(self, parent, label_state):
  25.         label = label_state[0]
  26.         self.btnStates = label.split()
  27.         self.state = label_state[1]
  28.         Button.__init__(self, parent, text=label, command=self.DoAction)
  29.         btnList = [] # an empty list
  30.         for rowNum, rowTuple in enumerate(buttonData):
  31.             for colNum, constTuple in enumerate(rowTuple):
  32.                 keyButton=KeyButton(root, buttonData[constTuple]) #I put this in... NEED INNER MOST DATA!
  33.                 keyButton.grid(row=rowNum, column=colNum)
  34.                 btnList.append(keyButton) # a linerar list of all the buttons.
  35.  
  36.  
  37.         nColumns = 3
  38.         nRows = len(buttonData)/nColumns
  39.  
  40.     def DoAction(self):
  41.         try:
  42.             print self.btnStates[self.state]
  43.         except IndexError:
  44.             print "No such state"
  45.     def SetState(self, state):
  46.         self.state = state
  47.  
  48.  
  49. if __name__ == "__main__":
  50.     root = Tk()
  51.     root.mainloop()
  52.  
  53.  
I tried some stuff, just trying to figure out what is stopping the buttons from building, but I can't figure it out....
Mar 14 '07 #15
TMS
119 New Member
ok, well, part of the problem is that I'm not calling KeyButton anywhere. So, I added KeyButton().mainloop() to just below root=Tk() and this is the error message I get:

Traceback (most recent call last):
File "C:\Python25\buttonTest.pyw", line 52, in <module>
KeyButton().mainloop()
TypeError: __init__() takes exactly 3 arguments (1 given)

meaning that I didn't call it right. So, with your help, I'm getting closer, I'm sure... but still needs help. Thank you for helping me with this!
Mar 14 '07 #16
bartonc
6,596 Recognized Expert Expert
I ran this. Some stuff you have in there, you'll have to work out. Mostly getting quotes right, I think (but I don't really see what you're trying to do with the [].
Expand|Select|Wrap|Line Numbers
  1. from Tkinter import *
  2. buttonData = \
  3. (
  4. ## ( ('~\n`', 1), ('!\n1', 1), ('@\n2', 1), ('#\n3', 1), ('$\n4', 1),
  5. ## ('%\n5', 1), ('^\n6', 1), ('&\n7', 1), ('*\n8', 1), ('(\n9', 1),
  6. ## (')\n0', 1), ('_\n-', 1), ('+\n=', 1), ('Backspace', 2)),
  7.  
  8.  (('Tab', 2), ('Q', 1), ('W', 1), ('E', 1), ('R', 1), ('T', 1),
  9.  ('Y', 1), ('U', 1), ('I', 1), ('O', 1), ('P', 1), ('{\n[', 1),
  10.  ('}\n]', 1), ('|\n\\', 1)),
  11.  
  12.  (('CapsLock', 2), ('A', 1), ('S', 1), ('D', 1), ('F', 1), ('G', 1),
  13.  ('H', 1), ('J', 1), ('K', 1), ('L', 1), (':\n;', 1), ('"\n\'', 1),
  14.  ('Enter', 2)),
  15.  
  16.  (('Shift', 2), ('Z', 1), ('X', 1), ('C', 1), ('V', 1), ('B', 1),
  17.  ('N', 1), ('M', 1), ('<\n,', 1), ('>\n.', 1), ('?\n/', 1), ('Shift', 3)),
  18.  
  19.  (('Ctrl', 2), ('Alt', 2), ('Space', 7), ('Alt', 2), ('Ctrl', 2)),
  20. )
  21.  
  22.  
  23. class KeyButton(Button):
  24.     def __init__(self, parent, label_state):
  25.         label = label_state[0]
  26.         self.btnStates = label.split()
  27.         self.state = label_state[1]
  28.         Button.__init__(self, parent, text=label, command=self.DoAction)
  29.  
  30.  
  31.     def DoAction(self):
  32.         try:
  33.             print self.btnStates[self.state]
  34.         except IndexError:
  35.             print "No such state"
  36.     def SetState(self, state):
  37.         self.state = state
  38.  
  39.  
  40. if __name__ == "__main__":
  41.     root = Tk()
  42.  
  43.     btnList = [] # an empty list
  44.     for rowNum, rowTuple in enumerate(buttonData):
  45.         for colNum, constTuple in enumerate(rowTuple):
  46.             keyButton=KeyButton(root, constTuple) #I put this in... NEED INNER MOST DATA!
  47.             keyButton.grid(row=rowNum, column=colNum)
  48.             btnList.append(keyButton) # a linerar list of all the buttons.
  49.  
  50.  
  51.     root.mainloop()
  52.  
Mar 14 '07 #17
bartonc
6,596 Recognized Expert Expert
I ran this. Some stuff you have in there, you'll have to work out. Mostly getting quotes right, I think (but I don't really see what you're trying to do with the [].
Expand|Select|Wrap|Line Numbers
  1. from Tkinter import *
  2. buttonData = \
  3. (
  4. ## ( ('~\n`', 1), ('!\n1', 1), ('@\n2', 1), ('#\n3', 1), ('$\n4', 1),
  5. ## ('%\n5', 1), ('^\n6', 1), ('&\n7', 1), ('*\n8', 1), ('(\n9', 1),
  6. ## (')\n0', 1), ('_\n-', 1), ('+\n=', 1), ('Backspace', 2)),
  7.  
If you hit reply, and read just above, you'll see what got copied to my script. The Code view seems right. You should be able to work this out with your original.
Mar 14 '07 #18
bartonc
6,596 Recognized Expert Expert
If you hit reply, and read just above, you'll see what got copied to my script. The Code view seems right. You should be able to work this out with your original.
OK. I worked it out:
Expand|Select|Wrap|Line Numbers
  1. from Tkinter import *
  2. buttonData = \
  3. (
  4.  ( ('~\n`', 1), ('!\n1', 1), ('@\n2', 1), ('#\n3', 1), ('$\n4', 1),
  5.  ('%\n5', 1), ('^\n6', 1), ('&\n7', 1), ('*\n8', 1), ('(\n9', 1),
  6.  (')\n0', 1), ('_\n-', 1), ('+\n=', 1), ('Backspace', 2)),
  7.  
  8.  (('Tab', 2), ('Q', 1), ('W', 1), ('E', 1), ('R', 1), ('T', 1),
  9.  ('Y', 1), ('U', 1), ('I', 1), ('O', 1), ('P', 1), ('{\n[', 1),
  10.  ('}\n]', 1), ('|\n\\', 1)),
  11.  
  12.  (('CapsLock', 2), ('A', 1), ('S', 1), ('D', 1), ('F', 1), ('G', 1),
  13.  ('H', 1), ('J', 1), ('K', 1), ('L', 1), (':\n;', 1), ('"\n\'', 1),
  14.  ('Enter', 2)),
  15.  
  16.  (('Shift', 2), ('Z', 1), ('X', 1), ('C', 1), ('V', 1), ('B', 1),
  17.  ('N', 1), ('M', 1), ('<\n,', 1), ('>\n.', 1), ('?\n/', 1), ('Shift', 3)),
  18.  
  19.  (('Ctrl', 2), ('Alt', 2), ('Space', 7), ('Alt', 2), ('Ctrl', 2)),
  20. )
  21.  
  22.  
  23. class KeyButton(Button):
  24.     def __init__(self, parent, label_state):
  25.         label = label_state[0]
  26.         self.btnStates = label.split()
  27.         self.state = label_state[1]
  28.         Button.__init__(self, parent, text=label, command=self.DoAction)
  29.  
  30.  
  31.     def DoAction(self):
  32.         try:
  33.             print self.btnStates[self.state]
  34.         except IndexError:
  35.             print "No such state"
  36.     def SetState(self, state):
  37.         self.state = state
  38.  
  39.  
  40. if __name__ == "__main__":
  41.     root = Tk()
  42.  
  43.     btnList = [] # an empty list
  44.     for rowNum, rowTuple in enumerate(buttonData):
  45.         for colNum, constTuple in enumerate(rowTuple):
  46.             keyButton=KeyButton(root, constTuple) #I put this in... NEED INNER MOST DATA!
  47.             keyButton.grid(row=rowNum, column=colNum)
  48.             btnList.append(keyButton) # a linerar list of all the buttons.
  49.  
  50.  
  51.     root.mainloop()
  52.  
Mar 14 '07 #19
bartonc
6,596 Recognized Expert Expert
I've gotten a better understanding, so here's a big head start. I've begun formating the screen for you.
Expand|Select|Wrap|Line Numbers
  1. from Tkinter import *
  2. buttonData = \
  3. (
  4.  ((), (), (), ('~\n`', 1), ('!\n1', 1), ('@\n2', 1), ('#\n3', 1), ('$\n4', 1),
  5.  ('%\n5', 1), ('^\n6', 1), ('&\n7', 1), ('*\n8', 1), ('(\n9', 1),
  6.  (')\n0', 1), ('_\n-', 1), ('+\n=', 1), ('Backspace', 2)),
  7.  
  8.  ((), ('Tab', 2), (), ('Q', 1), ('W', 1), ('E', 1), ('R', 1), ('T', 1),
  9.  ('Y', 1), ('U', 1), ('I', 1), ('O', 1), ('P', 1), ('{\n[', 1),
  10.  ('}\n]', 1), ('|\n\\', 1)),
  11.  
  12.  (('CapsLock', 3), (), (), ('A', 1), ('S', 1), ('D', 1), ('F', 1), ('G', 1),
  13.  ('H', 1), ('J', 1), ('K', 1), ('L', 1), (':\n;', 1), ('"\n\'', 1),
  14.  ('Enter', 2)),
  15.  
  16.  ((), ('Shift', 2), (), ('Z', 1), ('X', 1), ('C', 1), ('V', 1), ('B', 1),
  17.  ('N', 1), ('M', 1), ('<\n,', 1), ('>\n.', 1), ('?\n/', 1), ('Shift', 3)),
  18.  
  19.  ((), ('Ctrl', 2), (), ('Alt', 2), (), ('Space', 5), (), (), (), (), ('Alt', 2), (), ('Ctrl', 2)),
  20. )
  21.  
  22.  
  23. class KeyButton(Button):
  24.     def __init__(self, parent, label):
  25.         states = label.split('\n')
  26.         if len(states) < 2:
  27.             states.append(label)
  28.         self.btnStates = states
  29.         self.state = 0
  30.         Button.__init__(self, parent, text=label, command=self.DoAction)
  31.  
  32.  
  33.     def DoAction(self):
  34.         try:
  35.             print self.btnStates[self.state]
  36.         except IndexError:
  37.             print "No such state"
  38.  
  39.     def SetState(self, state):
  40.         self.state = state
  41.  
  42.  
  43. if __name__ == "__main__":
  44.     root = Tk()
  45.  
  46.     btnList = [] # an empty list
  47.     for rowNum, rowTuple in enumerate(buttonData):
  48.         for colNum, constTuple in enumerate(rowTuple):
  49.             if constTuple:
  50.                 keyButton=KeyButton(root, constTuple[0]) # Send the lable to the keyButton
  51.                 keyButton.grid(row=rowNum, column=colNum, columnspan=constTuple[1], sticky=EW)
  52.                 btnList.append(keyButton) # a linerar list of all the buttons.
  53.  
  54.  
  55.     root.mainloop()
  56.  
Mar 14 '07 #20
TMS
119 New Member
Awesome.

One question... why build the buttons in the test program? If I was to call it from a command line, it wouldn't work, right? Just curious.
Mar 14 '07 #21
bartonc
6,596 Recognized Expert Expert
Awesome.

One question... why build the buttons in the test program? If I was to call it from a command line, it wouldn't work, right? Just curious.
If you run this as a script (command line counts as such), __name__ will be __main__. We do this so that later you can reuse the class from another module with import.
Mar 14 '07 #22
TMS
119 New Member
ok, thank you. It looks really good. I did some space formatting and now I'm working on backspace and such. This is what it looks like with the formatting:


Expand|Select|Wrap|Line Numbers
  1. from Tkinter import *
  2. buttonData = \
  3. (
  4.  ( ('  ~  \n  `  \n ', 1), ('   !  \n 1 \n ', 1),  ('  @  \n  2  \n', 1), ('   #  \n   3  \n', 1), ('   $  \n  4  \n', 1), 
  5.  ('   %   \n  5   \n', 1), ('  ^  \n   6   \n', 1), ('   &   \n  7  \n', 1), ('   *   \n   8  \n', 1), ('  (   \n   9   \n', 1), 
  6.  ('  )   \n  0  \n', 1), ('  _  \n   -   \n', 1), ('  +  \n  =   \n', 1),  (' \n    Backspace    \n', 6), (),  ()),
  7.  (('  Tab  \n', 2), (),  (' Q \n', 1), (' W \n', 1), (' E \n', 1), (' R \n', 1), (' T \n', 1),
  8.  (' Y \n', 1), (' U \n  ', 1), (' I  \n ', 1), (' O \n ', 1), (' P \n ', 1), (' {  \n  [  ', 1), 
  9.  ('    }   \n    ]   ', 1 ), ('       |       \n   \\   ', 1) ),
  10.  (('Caps Lock\n', 3), (), (), ('A\n', 1), ('S\n', 1), ('D\n', 1), ('F\n', 1), ('G\n', 1),
  11.  ('H\n', 1), ('J\n', 1), ('K\n', 1), ('L\n', 1), (':\n;', 1), ('"\n\'', 1),
  12.  ('Enter\n ', 2)),
  13.  (('Shift\n', 3), (), (), ('Z\n', 1), ('X\n', 1), ('C\n', 1), ('V\n', 1), ('B\n', 1),
  14.  ('N\n', 1), ('M\n', 1), ('<\n,', 1), ('>\n.', 1), ('?\n/', 1), ('Shift\n', 2)),
  15.  (('\nCtrl', 3), (), (), ('\nAlt', 2), (), ('\n          Space              ', 7), (), (),(),(),(), (), ('\nAlt', 2), (), ('\nCtrl', 2)),
  16. )
  17.  
  18. class KeyButton(Button):
  19.     def __init__(self, parent, label):
  20.         states = label.split('\n')
  21.         if len(states) < 2:
  22.             states.append(label)
  23.         self.btnStates = states
  24.         self.state = 0
  25.         Button.__init__(self, parent, text=label, command=self.DoAction)
  26.     def DoAction(self):
  27.         try:
  28.             print self.btnStates[self.state]
  29.         except IndexError:
  30.             print "No such state"
  31.     def SetState(self, state):
  32.         self.state = state
  33.  
  34. if __name__ == "__main__":
  35.     root = Tk()
  36.     btnList = [] # an empty list
  37.     for rowNum, rowTuple in enumerate(buttonData):
  38.         for colNum, constTuple in enumerate(rowTuple):
  39.             if constTuple:
  40.                 keyButton=KeyButton(root, constTuple[0]) # Send the lable to the keyButton
  41.                 keyButton.grid(row=rowNum, column=colNum, columnspan=constTuple[1], sticky=EW)
  42.                 btnList.append(keyButton) # a linerar list of all the buttons.
  43.  
  44.     root.mainloop()
  45.  
  46.  
  47.  
I'm trying to make it look like a keyboard, and on my machine it works. I will try it on a laptop later. Thank you so much for the BIG push. I'm definitely more optimistic.

TMS
Mar 14 '07 #23
TMS
119 New Member
OK, I don't get it. HOW did you get the space bar to print a space? I see that it works, but I don't see where you told it to do that! Please point it out, I've been going through the code and .... well, its a mystery!
Mar 14 '07 #24
bartonc
6,596 Recognized Expert Expert
ok, thank you. It looks really good. I did some space formatting and now I'm working on backspace and such. This is what it looks like with the formatting:


Expand|Select|Wrap|Line Numbers
  1. from Tkinter import *
  2. buttonData = \
  3. (
  4.  ( ('  ~  \n  `  \n ', 1), ('   !  \n 1 \n ', 1),  ('  @  \n  2  \n', 1), ('   #  \n   3  \n', 1), ('   $  \n  4  \n', 1), 
  5.  ('   %   \n  5   \n', 1), ('  ^  \n   6   \n', 1), ('   &   \n  7  \n', 1), ('   *   \n   8  \n', 1), ('  (   \n   9   \n', 1), 
  6.  ('  )   \n  0  \n', 1), ('  _  \n   -   \n', 1), ('  +  \n  =   \n', 1),  (' \n    Backspace    \n', 6), (),  ()),
  7.  (('  Tab  \n', 2), (),  (' Q \n', 1), (' W \n', 1), (' E \n', 1), (' R \n', 1), (' T \n', 1),
  8.  (' Y \n', 1), (' U \n  ', 1), (' I  \n ', 1), (' O \n ', 1), (' P \n ', 1), (' {  \n  [  ', 1), 
  9.  ('    }   \n    ]   ', 1 ), ('       |       \n   \\   ', 1) ),
  10.  (('Caps Lock\n', 3), (), (), ('A\n', 1), ('S\n', 1), ('D\n', 1), ('F\n', 1), ('G\n', 1),
  11.  ('H\n', 1), ('J\n', 1), ('K\n', 1), ('L\n', 1), (':\n;', 1), ('"\n\'', 1),
  12.  ('Enter\n ', 2)),
  13.  (('Shift\n', 3), (), (), ('Z\n', 1), ('X\n', 1), ('C\n', 1), ('V\n', 1), ('B\n', 1),
  14.  ('N\n', 1), ('M\n', 1), ('<\n,', 1), ('>\n.', 1), ('?\n/', 1), ('Shift\n', 2)),
  15.  (('\nCtrl', 3), (), (), ('\nAlt', 2), (), ('\n          Space              ', 7), (), (),(),(),(), (), ('\nAlt', 2), (), ('\nCtrl', 2)),
  16. )
  17.  
  18. class KeyButton(Button):
  19.     def __init__(self, parent, label):
  20.         states = label.split('\n')
  21.         if len(states) < 2:
  22.             states.append(label)
  23.         self.btnStates = states
  24.         self.state = 0
  25.         Button.__init__(self, parent, text=label, command=self.DoAction)
  26.     def DoAction(self):
  27.         try:
  28.             print self.btnStates[self.state]
  29.         except IndexError:
  30.             print "No such state"
  31.     def SetState(self, state):
  32.         self.state = state
  33.  
  34. if __name__ == "__main__":
  35.     root = Tk()
  36.     btnList = [] # an empty list
  37.     for rowNum, rowTuple in enumerate(buttonData):
  38.         for colNum, constTuple in enumerate(rowTuple):
  39.             if constTuple:
  40.                 keyButton=KeyButton(root, constTuple[0]) # Send the lable to the keyButton
  41.                 keyButton.grid(row=rowNum, column=colNum, columnspan=constTuple[1], sticky=EW)
  42.                 btnList.append(keyButton) # a linerar list of all the buttons.
  43.  
  44.     root.mainloop()
  45.  
  46.  
  47.  
I'm trying to make it look like a keyboard, and on my machine it works. I will try it on a laptop later. Thank you so much for the BIG push. I'm definitely more optimistic.

TMS
I guess that it's time to talk about inheritance: I designed this class for the general rule that a button has 2 values. The values come from the incoming label argument:
Expand|Select|Wrap|Line Numbers
  1. '  ~  \n  ` '.split('\n')  # for example
becomes
Expand|Select|Wrap|Line Numbers
  1. ['  ~  ', ' ` ']
which is saved in self.btnStates (should probably be self.btnStateText)
DoAction() the looks at self.state and decides which of these to print.
I added some specialty code for buttons with no newline in the label that gave both states the same value, but at the time I was thinking that is was time for a new subclass of KeyButton or a rewrite of this one that takes more arguments ((say) label, [char1, char2]). Of course, the easiest thing to do is replace "space" with " " (I'm not sure what replacing "tab" with '\t' will do, though).
Expand|Select|Wrap|Line Numbers
  1. class KeyButton(Button):
  2.     def __init__(self, parent, label):
  3.         statesText = label.split('\n') ### see explanation above ##
  4.         if len(statesText) < 2:
  5.             statesText.append(label)
  6.         self.btnStateText= statesText
  7.         self.state = 0
  8.         Button.__init__(self, parent, text=label, command=self.DoAction)
  9.  
  10.     def DoAction(self):
  11.         try:
  12.             print self.btnStateText[self.state]
  13.         except IndexError:
  14.             print "No such state"
  15.     def SetState(self, state):
  16.         self.state = state
  17.  
Mar 14 '07 #25
TMS
119 New Member
right... I'm looking at the code and I don't see where space is replaced with " ". I have an understanding of how you did the \n thing, so that only one of the letters or chars is printed, but I don't see where you added the functionality for "space". You have defined an action, I see that, and defined states, but I'm looking specifically where the action of the spacebar is. thanks for your patience, I'm just amazed at this whole thing!
Mar 14 '07 #26
TMS
119 New Member
nevermind... I know why.... I did a newline and its printing the space from the top line. LOL. OK, nevermind.

tms
Mar 14 '07 #27
TMS
119 New Member
Well, my teacher tells me the approach is all wrong. As usual, its his way or no way. Really frustrating since there is no way to develop my own style when I get things wrong if I don't do it the way he wants me to. sigh..........

He said the code makes the assumption that the button label determines the states and that each key maintains its own state, and that is wrong. The state applies to the whole keyboard, so 'state' should not be an attribute of the button. I suppose that means different layouts? OMG I wish I never took this class!

thanks for the help... sigh....
Mar 15 '07 #28
bartonc
6,596 Recognized Expert Expert
Well, my teacher tells me the approach is all wrong. As usual, its his way or no way. Really frustrating since there is no way to develop my own style when I get things wrong if I don't do it the way he wants me to. sigh..........
I think you're doing well and if you enjoy it or get to do your own project for fun you'll develop you own style. Then everbody elses way can be wrong.
He said the code makes the assumption that the button label determines the states and that each key maintains its own state, and that is wrong. The state applies to the whole keyboard, so 'state' should not be an attribute of the button.
This is a very good point. It does complicate things a bit, though.
I suppose that means different layouts?
It just means tweaking the class a little bit. That's the beauty of this type of OOP.
OMG I wish I never took this class!
Hang in there, you'll get it.
thanks for the help... sigh....
Sorry if I created the confusion that you're going through.
Mar 15 '07 #29
TMS
119 New Member
No... you didn't create the confusion.

I have a new question, and I'll start a new thread. Thank you again, I really learned some stuff from this process.

TMS
Mar 19 '07 #30
bartonc
6,596 Recognized Expert Expert
No... you didn't create the confusion.

I have a new question, and I'll start a new thread. Thank you again, I really learned some stuff from this process.

TMS
Any time, really!
Mar 19 '07 #31

Sign in to post your reply or Sign up for a free account.

Similar topics

3
6991
by: srijit | last post by:
Hello, Any idea - why the following code crashes on my Win 98 machine with Python 2.3? Everytime I run this code, I have to reboot my machine. I also have Win32all-157 installed. from Tkinter...
2
3218
by: Paul A. Wilson | last post by:
I'm new to Tkinter programming and am having trouble creating a reusable button bar... I want to be able to feed my class a dictionary of button names and function names, which the class will make....
2
5096
by: Zhang Le | last post by:
Hello, Is there a quick way to replace the content of a single item in tkinter's listbox? Currently my solution is to first delete the item, then insert a new item at the same position. I think...
1
3228
by: fedor | last post by:
Hi all, happy new year, I was trying to pickle a instance of a subclass of a tuple when I ran into a problem. Pickling doesn't work with HIGHEST_PROTOCOL. How should I rewrite my class so I can...
6
3095
by: phil | last post by:
I posted the following yesterday and got no response and did some testing simplifying the circumstances and it appears that deepcopy fails when the object to be copied contains a reference to a...
1
3581
by: Michael Yanowitz | last post by:
Hello: Below I have included a stripped down version of the GUI I am working on. It contains 2 dialog boxes - one main and one settings. It has the following problems, probably all related, that...
2
8153
by: Fuzzyman | last post by:
Hello all, I have some Tkinter buttons that display images. I would like to change these to 'active' images when the mouse is over the button. I see that the button widget can take an...
1
5202
by: yvesd | last post by:
hello i want to intercept tkinter python system events like wm_delete_window and if possible for any window, but the newest code I've produced give me an error : Traceback (most recent call...
5
2022
by: crystalattice | last post by:
I'm creating a shelve interface using Tkinter. I have a button that allows the user to modify an existing entry; when the button is clicked, a new TopLevel window appears with Entry boxes holding...
0
7125
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7203
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6885
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5462
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
4908
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4588
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3093
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1417
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
656
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.