Tkinter, add pressed buttons onto string display string, how to?

S

skanemupp

using tkinter and python i now have a small App (that will hopefully
soon be a fully functioning calculator) where u can push buttons and
the corresponding number or operator is shown.

when u press 1, "1" appears on the screen, pres + and "+" appears etc.

at the moment every output overwrites the previous so what i want to
do is obviosuly to add every new output to a string so that i can read
the string and perform the calculation.

so i want:
* when pushing the button push the token of the button onto a string
* display the new string, ie "1+2" for example
* want to be able to access this string when pressing calculate so i
can figure out which operators should
be done first so it can solve something like this: "(1+2*3)(3-4/2)"
and not just simple "1+2"-stuff.

do i have to have some global string-variable in the GUIframework
then? im not sure where to start...


here is the code:

#! /usr/bin/env python
from Tkinter import *
import tkMessageBox

class GUIFramework(Frame):
"""This is the GUI"""

def __init__(self, master=None):
"""Initialize yourself"""

"""Initialise the base class"""
Frame.__init__(self,master)

"""Set the Window Title"""
self.master.title("Calculator")

"""Display the main window"
with a little bit of padding"""
self.grid(padx=10,pady=10)
self.CreateWidgets()



def CreateWidgets(self):

## """Create the Entry, set it to be a bit wider"""
## self.enText = Entry(self)
## self.enText.grid(row=0, column=0, columnspan=3)

"""Create the Button, set the text and the
command that will be called when the button is clicked"""
self.btnDisplay = Button(self, text="calculate!",
state=DISABLED)
self.btnDisplay.grid(row=0, column=31)


self.btnDisplay = Button(self,text='1',command=lambda
n=1:self.Display(n),width=1,height=1)
self.btnDisplay.grid(row=3, column=0, padx=5, pady=5)

self.btnDisplay = Button(self,text='2',command=lambda
n=2:self.Display(n),width=1,height=1)
self.btnDisplay.grid(row=3, column=1, padx=5, pady=5)

self.btnDisplay = Button(self,text='3',command=lambda
n=3:self.Display(n),width=1,height=1)
self.btnDisplay.grid(row=3, column=2, padx=5, pady=5)

self.btnDisplay = Button(self,text='+',command=lambda
n="+":self.Display(n),width=1,height=1)
self.btnDisplay.grid(row=3, column=3, padx=5, pady=5)

self.btnDisplay = Button(self,text='4',command=lambda
n=4:self.Display(n),width=1,height=1)
self.btnDisplay.grid(row=4, column=0, padx=5, pady=5)

self.btnDisplay = Button(self,text='5',command=lambda
n=5:self.Display(n),width=1,height=1)
self.btnDisplay.grid(row=4, column=1, padx=5, pady=5)

self.btnDisplay = Button(self,text='6',command=lambda
n=6:self.Display(n),width=1,height=1)
self.btnDisplay.grid(row=4, column=2, padx=5, pady=5)

self.btnDisplay = Button(self,text='-',command=lambda
n="-":self.Display(n),width=1,height=1)
self.btnDisplay.grid(row=4, column=3, padx=5, pady=5)

self.btnDisplay = Button(self,text='7',command=lambda
n=7:self.Display(n),width=1,height=1)
self.btnDisplay.grid(row=5, column=0, padx=5, pady=5)

self.btnDisplay = Button(self,text='8',command=lambda
n=8:self.Display(n),width=1,height=1)
self.btnDisplay.grid(row=5, column=1, padx=5, pady=5)

self.btnDisplay = Button(self,text='9',command=lambda
n=9:self.Display(n),width=1,height=1)
self.btnDisplay.grid(row=5, column=2, padx=5, pady=5)

self.btnDisplay = Button(self,text='*',command=lambda
n="*":self.Display(n),width=1,height=1)
self.btnDisplay.grid(row=5, column=3, padx=5, pady=5)

self.btnDisplay = Button(self,text='0',command=lambda
n=0:self.Display(n),width=1,height=1)
self.btnDisplay.grid(row=6, column=0, padx=5, pady=5)

self.btnDisplay = Button(self,text='C',command=lambda
n="C":self.Display(n),width=1,height=1)
self.btnDisplay.grid(row=6, column=1, padx=5, pady=5)

self.btnDisplay = Button(self,text='r',command=lambda
n="r":self.Display(n),width=1,height=1)
self.btnDisplay.grid(row=6, column=2, padx=5, pady=5)

self.btnDisplay = Button(self,text='/',command=lambda
n="/":self.Display(n),width=1,height=1)
self.btnDisplay.grid(row=6, column=3, padx=5, pady=5)




def Display(self, number):
#print number
self.lbText = Label(self, text=number)
self.lbText.grid(row=0, column=0)



if __name__ == "__main__":
guiFrame = GUIFramework()
guiFrame.mainloop()
 
7

7stud

using tkinter and python i now have a small App (that will hopefully
soon be a fully functioning calculator) where u can push buttons and
the corresponding number or operator is shown.

when u press 1, "1" appears on the screen, pres + and "+" appears etc.

at the moment every output overwrites the previous so what i want to
do is obviosuly to add every new output to a string so that i can read
the string and perform the calculation.

so i want:
* when pushing the button push the token of the button onto a string
* display the new string, ie "1+2" for example
* want to be able to access this string when pressing calculate so i
can figure out which operators should
be done first so it can solve something like this: "(1+2*3)(3-4/2)"
and not just simple "1+2"-stuff.

do i have to have some global string-variable in the GUIframework
then? im not sure where to start...

input = "hello"
input += " world"
print input

--output:--
hello

A caculator program is pretty complex. Based on your rudimentary
questions, I don't think you have enough programming experience to
tackle a project like that yet.
 
7

7stud

input = "hello"
input += " world"
print input

--output:--
hello

A caculator program is pretty complex.  Based on your rudimentary
questions, I don't think you have enough programming experience to
tackle a project like that yet.

--output:--
hello world
 
S

skanemupp

input = "hello"
input += " world"
print input

this i know. im wondering how to handle the variable in the actual
program. this exception i get:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__
return self.func(*args)
File "C:\Users\saftarn\Desktop\guiexperiments\calculatorGUI.py",
line 48, in <lambda>
self.btnDisplay = Button(self,text='+',command=lambda
n="+":self.Display(n),width=1,height=1)
File "C:\Users\saftarn\Desktop\guiexperiments\calculatorGUI.py",
line 92, in Display
str = number + str
UnboundLocalError: local variable 'str' referenced before assignment

A caculator program is pretty complex. Based on your rudimentary
questions, I don't think you have enough programming experience to
tackle a project like that yet.

nah ill be fine. im new to python, not to programming.
 
M

Marc 'BlackJack' Rintsch

this i know. im wondering how to handle the variable in the actual
program. this exception i get:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__
return self.func(*args)
File "C:\Users\saftarn\Desktop\guiexperiments\calculatorGUI.py",
line 48, in <lambda>
self.btnDisplay = Button(self,text='+',command=lambda
n="+":self.Display(n),width=1,height=1)
File "C:\Users\saftarn\Desktop\guiexperiments\calculatorGUI.py",
line 92, in Display
str = number + str
UnboundLocalError: local variable 'str' referenced before assignment

Just like the message says: You are trying to use `str` (on the right hand
side of the assignment) before anything is bound to that name.

Ciao,
Marc 'BlackJack' Rintsch
 
S

skanemupp

Just like the message says: You are trying to use `str` (on the right hand
side of the assignment) before anything is bound to that name.

Ciao,
Marc 'BlackJack' Rintsch


i know but i want the variable str(which i found out is a reserved
word so i changed it) to be accessible all over __init__ right?
so i tried to delcare it in __init__ in the beginning of the framework
class but then when i access it in the method Display i get that
error.

so how should i declare this variable to be able to access it
everywhere?

i want another method "calculate" that can access the same string
later and do the calculations(writing some other code now that will
read and interpret that).
 
G

Gabriel Genellina

i know but i want the variable str(which i found out is a reserved
word so i changed it) to be accessible all over __init__ right?
so i tried to delcare it in __init__ in the beginning of the framework
class but then when i access it in the method Display i get that
error.

so how should i declare this variable to be able to access it
everywhere?

It should be an instance attribute: self.expr by example.
Remember to initialize it with '' in __init__
i want another method "calculate" that can access the same string
later and do the calculations(writing some other code now that will
read and interpret that).

Ok, use self.expr in calculate. Something like this:

def calculate(self):
self.expr = str(eval(self.expr))

and probably force a repaint of the calculator display. You may want to
use a try/except block to catch any errors.
 
7

7stud

Just like the message says: You are trying to use `str` (on the right hand
i know but i want the variable str(which i found out is a reserved
word so i changed it) to be accessible all over __init__ right?

"all over __init__" ? You could practice with a trivial example to
discover how things work in python:

def f():
num = 10
print num

f()

def g():
print num
num = 10

g()

so i tried to delcare it in __init__ in the beginning of the framework
class but then when i access it in the method Display i get that
error.

so how should i declare this variable to be able to access it
everywhere?

You don't declare variables in python. You just start using a
variable when you need it. In other words you don't do this:

string my_str
my_str = "hello"

You just write:

my_str = "hello"

i want another method "calculate" that can access the same string
later and do the calculations(writing some other code now that will
read and interpret that).

Does this look familiar:
 
S

Steve Holden

7stud said:
"all over __init__" ? You could practice with a trivial example to
discover how things work in python:

def f():
num = 10
print num

f()

def g():
print num
num = 10

g()



You don't declare variables in python. You just start using a
variable when you need it. In other words you don't do this:

string my_str
my_str = "hello"

You just write:

my_str = "hello"



Does this look familiar:

To pick nits, "str" is not a reserved word (normally referred to in
Python as s "keyword"). It's perfectly possible to write:
.... return "Fooled you!"
....
and have your program work. But it's not generally good practice to
*shadow* built-in names, even when nothing stops you from doing so,
simply because there is usually a group somewhere with an investment in
using the standard names, and you will make their lives more difficult.

regards
Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,989
Messages
2,570,207
Members
46,782
Latest member
ThomasGex

Latest Threads

Top