check entry inputs in tkinter using a function - python-2.7

I trying to create physics calculator using python tkinter but I find it quite difficult. I have done this calculator in Command line interface but I a bit different with tkinter. basically, I have 5 entry boxes and above each one of them a button. the user will insert values in three of them and should press the button on top of each unknown value to make the calculation and get the result. my main issue is how can I create a function that evaluates the inputs in my entry boxes and make the calculation then print the results inside the entry box. I made some coding but unfortunately the operation is not working due to few mistakes.
here is my coding part:
from Tkinter import *
import math
class calculator():
def is_positive_number(number): # validation function
if number <= 0:
return False
else :
return True
def value_of_time(prompt):
while True: # loop command for time
try:
valid = False
while not valid:
value = float((prompt))
if is_positive_number(value):
valid = True
return value
else :
valid = False
print ('I donot know what is happening')
except ValueError:
print("Oops, unfortunately this is a wrong input, please try again.")
#better try again... Return to the start of the loop
continue
else:
#value was successfully parsed!
#we're ready to exit the loop.
break
def input_of_box(prompt):
while True: # loop for initial velocity
try:
value = float(input(prompt))
return value
except ValueError:
print("Oops, we are you not typing a number, please try again.")
#better try again... Return to the start of the loop
continue
else:
#value was successfully parsed!
#we're ready to exit the loop.
break
# def minput(numberofinput):
if numberofinput == 1:
t = value_of_time("Enter the time that takes an object to accelerate in seconds:")
return
elif numberofinput == 2:
u = input_of_box("Enter the initial velocity in m/s:")
return
elif numberofinput == 2:
v = input_of_box("Enter the final velocity in m/s:")
return
def my_calculation(mvariables): # this function is to operate the calculation
if mvariables == 1:
a = (v-u) /(t)
mentery1 = a
return
elif mvariables == 2:
v = u + a*t
mentery2 = v
return
elif mvariables == 3:
u = a*t - v
mentery3 = t
elif mvariables == 4:
t = (v - u)/a
mentery3 = t
return
elif mvariables == 5:
s = (v**2-u**2)/2*a
mentery4 = s
else:
print ('there is an error')
cal = Tk()
cal.configure(background='sky blue')
a = StringVar()
u = StringVar()
v = StringVar()
t = StringVar()
s = StringVar()
cal.geometry('650x420+350+225')
cal.title('Main Menu')
# here we start greating buttons and entry boxes
m_label = Label(text='Calculator',fg = 'Navy', font=("Helvetica", 20,"bold italic"), bg='sky blue')
m_label.pack()
button1 = Button(cal,text='A',fg='white',bg='dark green',bd =3, width=4, command= lambda : my_calculation(1))
button1.place(x=92,y=210)
mentery1 = Entry(cal, textvariable = a ,width=10,bd =3)
mentery1.place(x=82,y=240)
button2 = Button(cal,text='U',fg='white',bg='dark green',bd =3, width=4, command= lambda : my_calculation(3))
button2.place(x=192,y=210)
mentery2 = Entry(cal, textvariable = u ,width=10,bd =3)
mentery2.place(x=182,y=240)
button3 = Button(cal,text='V',fg='white',bg='dark green',bd =3, width=4, command= lambda : my_calculation(2))
button3.place(x=292,y=210)
mentery3 = Entry(cal, textvariable = v ,width=10,bd =3)
mentery3.place(x=282,y=240)
button4 = Button(cal,text='T',fg='white',bg='dark green',bd =3, width=4,command= lambda : my_calculation(4))
button4.place(x=392,y=210)
mentery4 = Entry(cal, textvariable = t ,width=10,bd =3)
mentery4.place(x=382,y=240)
button5 = Button(cal,text='S',fg='white',bg='dark green',bd =3, width=4,command= lambda : my_calculation(5))
button5.place(x=492,y=210)
mentery5 = Entry(cal, textvariable = s , width=10,bd =3)
mentery5.place(x=482,y=240)
# end of button commands
app = calculator()
app.mainloop()

For validating the input, do the following:
def returnValidatedInput(entry):
value = entry.get() # Get the text in the 'entry' widget
evaluation = eval(value) # Evaluate 'value'
return evaluation
And for inserting the answers into the entries (it's not called printing the answers into the entries):
def insertAnswer(entry, answer):
entry.delete(0, 'end') # Be sure the entry is empty, if it is not, clear it
entry.insert(END, str(answer)) # Insert the answer into the 'entry' widget.

Related

If loop in tkinter - button pressed

How to get tkinter to enter the if loop when button pressed to print? I do not want the print command to be in the button function.
Code:
from tkinter import *
class Player:
N = 0
def __init__(self, name, points):
# instance variables goes here
self.name = name
self.score = points
# increment class variable
Player.N = Player.N+1
class G_501:
def __init__(self, players=[]):
self.NoPlayers = len(players)
print("Number of players",self.NoPlayers)
Spillere = []
Score = []
Runde = 0
for i in range(0, len(players)):
P = Player(players[i], 501)
print("Player", Player.N, P.name, "- Point:", P.score)
Spillere.append(P.name)
Score.append(P.score)
Score = list(map(int, Score))
root = Tk()
c = [False]
def half_bull(c, event=None):
c.append(True)
return c
b1 = Button(root, text="Half Bull", bg="green", fg="black", command=lambda c=c: half_bull(c))
b1.pack()
print(c)
if c[-1] == True:
print("Fedt")
root.mainloop()
S = G_501(["Chr"])
Only need help with the tkinter part... Thanks!

Generate a bunch of tkinter checkbuttons and read the status of all those radio buttons at once

I have a tkinter class which reads some data into a couple of lists. From this now i have created a dictionary for creating checkbuttons.
I'm trying to create those checkbuttons in a new window() with a button to submit and read the stutus of those. I want this data to process.
def get_data(self):
self.flags = ["one","two","three", "four"]
self.tests = ["Jack","Queen","King","Ace"]
self.value = [11,12,13,1]
self.dict1 = {k:v for k,v in enumerate(self.flags,1)}
def get_status(self):
self.selectWindow = Toplevel(root)
self.selectWindow.title("Select Test Cases")
Submit_btn = Button(selectWindow, text="Submit", command=read_status )
for testcase in self.dict1:
self.dict1[testcase] = Variable()
l = Checkbutton(self.selectWindow,text=self.dict1[testcase], variable=self.dict1[testcase])
l.pack()
def read_status(self):
pass
From here I'm not able go ahead and read the status of checkbuttons and get those are checked. I need this data for further processing on tests(not actual lists given here I have few more). How to solve? Please let me know.
Checkbutton has a built in command function that can solve this problem. Every time you press a button that function is called, and you can print out the values of the buttons (0,1)
def get_data(self):
self.flags = ["one","two","three", "four"]
self.tests = ["Jack","Queen","King","Ace"]
self.value = [11,12,13,1]
self.dict1 = {k:v for k,v in enumerate(self.flags,1)}
def get_status(self):
self.selectWindow = Toplevel(self)
self.selectWindow.title("Select Test Cases")
self.get_data()
Submit_btn = Button(self.selectWindow, text="Submit", command=read_status ) # This button should be packed
Submit_btn.pack()
for testcase in self.dict1:
self.dict1[testcase] = Variable()
l = Checkbutton(self.selectWindow,text=self.dict1[testcase], variable=self.dict1[testcase], command=self.read_status) # Note the command
l.pack()
self.selectWindow.mainloop()
# Here comes the interesting part
def read_status(self):
for i,j in self.dict1.iteritems():
print j.get()
You forgot to use self and pack method:
Submit_btn = Button(self.selectWindow, text="Submit", command=self.read_status )
Submit_btn.pack()
Checkbutton's states are (0, 1) so use IntVar() to inspect the state:
...
self.dict1[testcase] = IntVar()
...
Then use IntVar get method:
def read_status(self):
for v in self.dict1:
print self.dict1[v].get()

Attribute error occurs when I run my GUI code in Python. Python gives me no information as to what the error is or what is causing it

This is my code and when i try to run it and use it by entering numbers into the entry fields, an attribute error occurs when i try to call on the entry variable. This is the message that appears:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in call
return self.func(*args)
File "F:\HomeWork\Yr13\Extended Project\Notepad++\Python27\Programs\GUI{c} menu+check+gen+Nth.py", line 224, in OnGenButtonClick
n= str(Prime_Generation(Prime_Gen.entryVariable5.get(),Prime_Gen.entryVariable6.get()))
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1845, in getattr
return getattr(self.tk, attr)
AttributeError: entryVariable5
any help would be greatly appreciated.
i have stuck on this problem for three days and have tried getting around the problem by using different functions and names and the error still occurs
import Tkinter
from Tkinter import *
import math
def SoS(limit):
numbers = range(3, limit+1, 2)
half = (limit)//2
initial = 4
for step in xrange(3, limit+1, 2):
for i in xrange(initial, half, step):
numbers[i-1] = 0
initial += 2*(step+1)
if initial > half:
plist = [2] + filter(None, numbers)
return plist
break
def S(m):
sieve = [True] * m
for i in xrange(3,(int(m**0.5)+1),2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((m-i*i-1)/(2*i)+1)
plist = [2] + [i for i in xrange(3,m,2) if sieve[i]]
return plist
def OTS(n):
n, correction = n-n%6+6, 2-(n%6>1)
sieve = [True] * (n/3)
for i in xrange(1,(int(n**0.5)/3)+1):
if sieve[i]:
k=3*i+1|1
sieve[ k*k/3 ::2*k] = [False] * ((n/6-k*k/6-1)/k+1)
sieve[k*(k-2*(i&1)+4)/3::2*k] = [False] * ((n/6-k*(k-2*(i&1)+4)/6-1)/k+1)
plist = [2,3] + [3*i+1|1 for i in xrange(1,n/3-correction) if sieve[i]]
return plist
def is_prime(num):
if num <= 3:
if num <= 1:
return False
return True
if not num % 2 or not num % 3:
return False
for i in xrange(5, int(num ** 0.5) + 1, 6):
if not num % i or not num % (i + 2):
return False
return True
def is_prime_multiple(Lower,Upper):
NumberList = dict()
if Lower%2 == 1:
for i in xrange(Lower, Upper,2):
NumberList[i] = is_prime(i)
else:
for i in xrange(Lower-1,Upper,2):
NumberList[i] = is_prime(i)
NumberList[1] = False
return [i for i in NumberList if NumberList[i] == True]
def Prime_Generation(L,U):
Lower = int(L)
Upper = int(U)
if Lower == 1:
if Upper < 92:
print SoS(Upper)
if Upper >= 92 and Upper < 2250:
print S(Upper)
if Upper >= 2250 :
print OTS(Upper)
else:
print sorted(is_prime_multiple(Lower,Upper))
def factors(n):
f = 3
fs = []
while n % 2 == 0:
fs.append(2)
n /= 2
while f*f <= n:
while n % f == 0:
fs.append(f)
n /= f
f += 2
if n > 1:
fs.append(n)
return fs
def Prime_Checker(N):
NStr = str(N)
N = int(N)
Nfs = factors(N)
for i in Nfs:
if i != N:
NfsStr = str(Nfs).strip('[]')
resultb = [NStr,' is not a prime. The prime factors of ',NStr,' are ',NfsStr]
return resultb.join()
else:
return N,' is a prime. The prime factors of ',N ,' are ',N
def PrimeFinderLamda(n,limit):
nums = range(3,limit,2)
for i in range(2, int(limit**0.5)):
nums = filter(lambda x: x == i or x % i, nums)
return [2]+nums
def NthPrime(N):
N = int(N)
Lower = 1
limit = N*N
if N == 1:
return 2
else:
return PrimeFinderLamda(N,limit)[N-1]
class Prime_app_tk(Tkinter.Tk):
def __init__(self,parent):
Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def Prime_Gen_Win(self):
Prime_Gen = Toplevel()
Prime_Gen.grid()
Prime_Gen.labelVariable3 = StringVar()
Title_label2 = Label(Prime_Gen,textvariable=Prime_Gen.labelVariable3,
relief = RAISED,fg="black",bg="white"
,font = "Arial")
Title_label2.grid(column=0,row=0,columnspan=4)
Prime_Gen.labelVariable3.set(u"Please enter the upper and lower limits of the prime number generation")
Prime_Gen.labelVariable4 = StringVar()
SubTitle_label1 = Label(Prime_Gen,textvariable=Prime_Gen.labelVariable4,fg="black",bg="white")
SubTitle_label1.grid(column=0,row=1,columnspan=4)
Prime_Gen.labelVariable4.set(u"(Please enter values no greater than 10 million)")
Prime_Gen.entryVariable5 = StringVar()
Prime_Gen.entry = Entry(Prime_Gen,textvariable=Prime_Gen.entryVariable5)
Prime_Gen.entry.grid(column=0,row=4)
Prime_Gen.entryVariable5.set(u"Lower.")
Prime_Gen.entryVariable6 = StringVar()
Prime_Gen.entry = Entry(Prime_Gen,textvariable=Prime_Gen.entryVariable6)
Prime_Gen.entry.grid(column=0,row=5)
Prime_Gen.entryVariable6.set(u"Upper.")
Genbutton = Button(Prime_Gen,text=u"Generate !",command=self.OnGenButtonClick #placing and aesthetics of button
,bg="yellow",relief=RAISED,padx=10,pady=10
,activebackground="red",activeforeground="white")
Genbutton.grid(column=0,row=6)
scrollbar = Scrollbar(Prime_Gen)
scrollbar.grid(column=1,row=8,sticky="ns")
Prime_Gen.Result_label = Text(Prime_Gen, yscrollcommand=scrollbar.set
,fg="blue",bg="white",wrap=WORD
,width=100,relief = SUNKEN)
Prime_Gen.Result_label.grid(column=0,row=8,columnspan=2)
scrollbar.config(command=Prime_Gen.Result_label.yview)
Prime_Gen.labelVariable = StringVar()
SubTitle_label = Label(Prime_Gen,textvariable=Prime_Gen.labelVariable,fg="black",bg="white")
SubTitle_label.grid(column=0,row=9,columnspan=4)
Prime_Gen.labelVariable.set(u"To see full list please click on the results\n and use the up and down arrows to scroll through the list")
Prime_Gen.grid_columnconfigure(0,weight=1)
Prime_Gen.resizable(True,True)
Prime_Gen.update()
Prime_Gen.geometry(Prime_Gen.geometry())
Prime_Gen.entry.focus_set()
Prime_Gen.entry.selection_range(0, Tkinter.END)
def OnGenButtonClick(Prime_Gen):
n= str(Prime_Generation(Prime_Gen.entryVariable5.get(),Prime_Gen.entryVariable6.get()))
Prime_Gen.Result_label.insert(END,"\nPrimes Found\n")
Prime_Gen.Result_label.insert(END,n)
Prime_Gen.entry.focus_set()
Prime_Gen.entry.selection_range(0, Tkinter.END)
def Prime_Check_Win(self):
Prime_Check = Toplevel()
Prime_Check.grid()
Prime_Check.labelVariable8 = StringVar()
Title_label3 = Label(Prime_Check,textvariable=Prime_Check.labelVariable8,
relief = RAISED,fg="black",bg="white"
,font = "Arial")
Title_label3.grid(column=0,row=0,columnspan=4)
Prime_Check.labelVariable8.set(u"Please enter a Number to be checked for primality")
Prime_Check.labelVariable9 = StringVar()
SubTitle_label3 = Label(Prime_Check,textvariable=Prime_Check.labelVariable9,fg="black",bg="white")
SubTitle_label3.grid(column=0,row=1,columnspan=4)
Prime_Check.labelVariable9.set(u"(Please enter values no greater than 10 million)")
Prime_Check.entryVariable = StringVar()
Prime_Check.entry = Entry(Prime_Check,textvariable=Prime_Check.entryVariable)
Prime_Check.entry.grid(column=0,row=2)
Prime_Check.entryVariable.set(u"Enter Number here.")
Checkbutton = Button(Prime_Check,text=u"Check !",command=self.OnCheckButtonClick
,bg="blue",fg="white",relief=RAISED,padx=10,pady=10
,activebackground="red",activeforeground="white")
Checkbutton.grid(column=0,row=4)
Prime_Check.labelVariable10 = StringVar()
Result_label2 = Message(Prime_Check,textvariable=Prime_Check.labelVariable10
,anchor="w",fg="blue",bg="white"
,width=500,relief = SUNKEN,padx=3,pady=3)
Result_label2.grid(column=0,row=5,columnspan=2,rowspan=100)
Prime_Check.labelVariable10.set(u"Hello")
Prime_Check.grid_columnconfigure(0,weight=1)
Prime_Check.resizable(True,False)
Prime_Check.update()
Prime_Check.geometry(Prime_Check.geometry())
Prime_Check.entry.focus_set()
Prime_Check.entry.selection_range(0, Tkinter.END)
def OnCheckButtonClick(Prime_Check):
Prime_Check.labelVariable10.set(Prime_Checker(Prime_Check.entryVariable.get())) #Had to call on prime gen and display results
Prime_Check.entry.focus_set()
Prime_Check.entry.selection_range(0, Tkinter.END)
def Nth_Prime_Win(self):
Nth_Prime = Toplevel()
Nth_Prime.grid()
Nth_Prime.labelVariable12 = StringVar()
Title_label = Label(Nth_Prime,textvariable=Nth_Prime.labelVariable12,
relief = RAISED,fg="black",bg="white"
,font = "Arial")
Title_label.grid(column=0,row=0,columnspan=4)
Nth_Prime.labelVariable12.set(u"Please enter the Nth prime you would like to find")
Nth_Prime.labelVariable13 = StringVar()
SubTitle_label = Label(Nth_Prime,textvariable=Nth_Prime.labelVariable13,fg="black",bg="white")
SubTitle_label.grid(column=0,row=1,columnspan=4)
Nth_Prime.labelVariable13.set(u"(Please enter values no greater than 664579")
Nth_Prime.entryVariable = StringVar()
Nth_Prime.entry = Entry(Nth_Prime,textvariable=Nth_Prime.entryVariable)
Nth_Prime.entry.grid(column=0,row=4)
Nth_Prime.entryVariable.set(u"Enter Number here.")
Genbutton = Button(Nth_Prime,text=u"Generate !",command=self.OnButtonNthClick
,bg="green",relief=RAISED,padx=10,pady=10
,activebackground="red",activeforeground="white")
Genbutton.grid(column=0,row=5)
Nth_Prime.labelVariable14 = StringVar()
Result_label = Message(Nth_Prime,textvariable=Nth_Prime.labelVariable14
,anchor="w",fg="blue",bg="white"
,width=1000,relief = SUNKEN,justify=LEFT,padx=3,pady=3)
Result_label.grid(column=0,row=6,columnspan=2,rowspan=100)
Nth_Prime.labelVariable14.set(u"Hello")
Nth_Prime.grid_columnconfigure(0,weight=1)
Nth_Prime.resizable(False,False)
Nth_Prime.update()
Nth_Prime.geometry(Nth_Prime.geometry())
Nth_Prime.entry.focus_set()
Nth_Prime.entry.selection_range(0, Tkinter.END)
def OnButtonNthClick(Nth_Prime):
Nth_Prime.labelVariable14.set(NthPrime(Nth_Prime.entryVariable.get()))
Nth_Prime.entry.focus_set()
Nth_Prime.entry.selection_range(0, Tkinter.END)
def initialize(self):
self.grid()
self.labelVariable1 = StringVar()
Title_label1 = Label(self,textvariable=self.labelVariable1,
relief = RAISED,fg="black",bg="white"
,font = "Arial")
Title_label1.grid(column=0,row=0,columnspan=4)
self.labelVariable1.set(u"Welcome to the Prime Program")
self.labelVariable2 = StringVar()
SubTitle_label = Label(self,textvariable=self.labelVariable2,fg="black",bg="white")
SubTitle_label.grid(column=0,row=1,columnspan=4)
self.labelVariable2.set(u"(Please select the function you would like to use)")
PrimeGenbutton = Button(self,text=u"Find Primes between 2 limits !",command=self.Prime_Gen_Win
,bg="yellow",relief=RAISED,padx=10,pady=10
,activebackground="red",activeforeground="white")
PrimeGenbutton.grid(column=0,row=3)
PrimeCheckbutton = Button(self,text=u"Check if a number is prime !",command=self.Prime_Check_Win
,bg="blue",fg="white",relief=RAISED,padx=14,pady=10
,activebackground="red",activeforeground="white")
PrimeCheckbutton.grid(column=0,row=4)
NthPrimebutton = Button(self,text=u"Find the Nth prime !",command=self.Nth_Prime_Win
,bg="green",relief=RAISED,padx=35,pady=10
,activebackground="red",activeforeground="white")
NthPrimebutton.grid(column=0,row=5)
self.grid_columnconfigure(0,weight=1)
self.resizable(False,False)
self.update()
self.geometry(self.geometry())
if __name__ == "__main__":
app = Prime_app_tk(None)
app.title('Prime Program')
app.mainloop()
There's no quick fix for your code. It attempts to be object-oriented, but is doing so incorrectly. You need to properly define your methods, and should also adhere to PEP8 naming conventions -- specifically, methods and functions should start with a lowercase, and classes should start with an uppercase. Because you don't follow PEP8, and because of the odd way you use Prime_Gen to mean different things at different times, your code is incredibly hard to understand.
The crux of the problem is that inside OnGenButtonClick, Prime_Gen is not what you think it is. It is an instance of Prime_app_tk rather than the value that you set the local variable Prime_Gen to in Prime_Gen_Win. Thus, any attributes you assigned to the original Prime_Gen don't exist in this other Prime_Gen.
The reason is that the button is defined like this:
Genbutton = Button(..., command=self.OnGenButtonClick, ...)
In this context, self is the instance of Prime_app_tk, so that becomes the parameter passed to OnGenButtonClick. Inside that function you call the parameter Prime_Gen, in spite of the universal convention to name it self. This causes confusion in your code, because you also have a local variable named Prime_Gen in the code that creates the toplevel window.

Trouble resetting / backtracking with variables

I've written a Cryptoquote Generator in Python using wxPython. I don't really have any problems with wxPython itself, but rather with resetting my variables. My program works this way: I have a button that generates an encrypted quote. Then, the user has a decode button they press to change one letter at a time. There is a button to reset the whole quote and a button to reset changes one step back at a time.
I have a base_copy variable to store the original encrypted quote. It is an empty list that is populated with the individual characters of the encrypted quote one at a time when on_generate_quote is called. It remains unchanged throughout the loop -- so that I may call on it with on_clear_all or on_clear_last to reset my encrypted quote. The problem is, if I use my decode_button to decode a letter, then use my clear_all_button, then decode_button again, my clear_all_button calls on a base_copy that has now been somehow tainted with changed letters that should only be in my split_cryptoquote copy. Why is this, since I never make an implicit call to alter base_copy? (I do, however, make a call in on_clear_all to set split_cryptoquote to base_copy, but this shouldn't change base_copy.)
#/------------------ wxPython GUI -----------------\
class MainWindow(wx.Frame):
quote = []
quote.append(quote_fetch(quotes))
split_cryptoquote = []
base_copy = []
split_buffer = []
buffer_origin = None
buffer_replace = None
quote_altered = False #Becomes true after first decoding change.
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, title="Cryptogrammar", size=(1000, 200))
self.CreateStatusBar()
self.txt = wx.StaticText(self, -1, "".join(MainWindow.split_cryptoquote), (20,30), (40,40))
self.txt.SetForegroundColour("WHITE")
#Menu
filemenu = wx.Menu()
menu_about = filemenu.Append(wx.ID_ABOUT, "&About", " Information about this program")
menu_how = filemenu.Append(HOW_TO, "&How to Play", " How to play Cryptogrammar")
menu_exit = filemenu.Append(wx.ID_EXIT,"E&xit", " Close Cryptogrammar")
#menuGenerate = filemenu.Append(wx.ID_NONE, "&Generate New", "Generate a new cryptogram")
#menu_bar
menu_bar = wx.MenuBar()
menu_bar.Append(filemenu, "&File")
self.SetMenuBar(menu_bar)
#Buttons
generate_button = wx.Button(self, -1, "&Generate Cryptogram")
decode_button = wx.Button(self, -1, "&Decode Letter")
clear_all_button = wx.Button(self, -1, "&Clear All Changes")
clear_last_button = wx.Button(self, -1, "Clear &Last Change")
answer_button = wx.Button(self, -1, "Show &Answer")
but_list = [generate_button, decode_button, clear_all_button, clear_last_button, answer_button]
#Sizers
self.sizer2 = wx.BoxSizer(wx.HORIZONTAL)
for i in range(0, 5):
self.sizer2.Add(but_list[i], 1, wx.EXPAND)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.txt, 1, wx.EXPAND)
self.sizer.Add(self.sizer2, 0, wx.EXPAND)
#Events
self.Bind(wx.EVT_MENU, self.on_about, menu_about)
self.Bind(wx.EVT_MENU, self.on_exit, menu_exit)
self.Bind(wx.EVT_MENU, self.on_how, menu_how)
self.Bind(wx.EVT_BUTTON, self.on_generate_quote, generate_button)
self.Bind(wx.EVT_BUTTON, self.on_decode, decode_button)
self.Bind(wx.EVT_BUTTON, self.on_answer, answer_button)
self.Bind(wx.EVT_BUTTON, self.on_clear_all, clear_all_button)
self.Bind(wx.EVT_BUTTON, self.on_clear_last, clear_last_button)
self.SetSizer(self.sizer)
self.SetAutoLayout(1)
self.sizer.Fit(self)
self.SetTitle("Cryptogrammar")
self.Centre()
def on_about(self, e):
dialogue = wx.MessageDialog(self, "A program for generating random cryptograms.\n\n\n\nCopyright 2014 Joshua Simmons\nVersion 0.1.0", "About Cryptogrammar", wx.OK)
dialogue.ShowModal()
dialogue.Destroy()
def on_exit(self, e):
self.Close(True)
def on_how(self, e):
dialogue = wx.MessageDialog(self, "HOW TO PLAY:\n\n\n--\tPress the 'Generate Cryptogram' to spawn a cryptogram.\n\n--\tUse the 'Decode Letter' to replace an encrypted letter with a letter of your choice. 'Decoded' letters will be lowercase to distinguish them.\n\n--\tUse the 'Clear Changes' button to reset the puzzle.\n\n--\t'Show Answer' solves the puzzle!", "How to play Cryptogrammar", wx.OK)
dialogue.ShowModal()
dialogue.Destroy()
def on_decode(self, e):
dialogue = wx.TextEntryDialog(self, "Which letter do you wish to change? Use format: 'a=e'", "Decode Letter", "")
dialogue.ShowModal()
decode = dialogue.GetValue()
#Text entry filter
match = re.search(r'\w+=\w+|^\d*$', decode)
if not match:
err = wx.MessageDialog(self, "That is not a correct entry format.", "Entry Error", style=wx.ICON_HAND)
err.ShowModal()
#Letter replacement
else:
if not MainWindow.quote_altered:
MainWindow.buffer_origin = decode[0].upper()
MainWindow.buffer_replace = decode[2].upper()
else:
for n in range(0, len(MainWindow.split_buffer)):
if MainWindow.split_buffer[n] == MainWindow.buffer_origin:
MainWindow.split_buffer[n] = MainWindow.buffer_replace.lower()
MainWindow.buffer_origin = decode[0].upper()
MainWindow.buffer_replace = decode[2].upper()
origin = decode[0].upper()
replace = decode[2].upper() #For resetting changes one at a time.
for n in range(0, len(MainWindow.split_cryptoquote)):
if MainWindow.split_cryptoquote[n] == origin:
MainWindow.split_cryptoquote[n] = replace.lower()
MainWindow.quote_altered = True
origin = None
replace = None
self.txt.SetLabel("".join(MainWindow.split_cryptoquote))
self.sizer.Layout()
dialogue.Destroy()
def on_generate_quote(self, e):
MainWindow.quote.pop()
MainWindow.quote.append(quote_fetch(quotes))
cryptoquote = generate_cryptogram(MainWindow.quote[0], encrypt_key(shuffle_alphabet()))
MainWindow.split_cryptoquote = []
MainWindow.base_copy = []
for i in cryptoquote:
MainWindow.split_cryptoquote.append(i)
MainWindow.base_copy.append(i)
MainWindow.split_buffer.append(i)
self.txt.SetLabel("".join(MainWindow.split_cryptoquote))
self.txt.SetForegroundColour("BLACK")
self.sizer.Layout()
def on_answer(self, e):
if len(MainWindow.base_copy) == 0:
err = wx.MessageDialog(self, "You haven't generated a puzzle yet, doofus!", "Encryption Error", style=wx.ICON_HAND)
err.ShowModal()
else:
self.txt.SetLabel(MainWindow.quote[0])
self.txt.SetForegroundColour("BLUE")
self.sizer.Layout()
def on_clear_last(self, e):
if MainWindow.quote_altered:
self.txt.SetLabel("".join(MainWindow.split_buffer))
else:
self.txt.SetLabel("".join(MainWindow.base_copy))
self.txt.SetForegroundColour("BLACK")
self.sizer.Layout()
def on_clear_all(self, e):
print MainWindow.base_copy
MainWindow.split_cryptoquote = MainWindow.base_copy
MainWindow.split_buffer = MainWindow.base_copy
MainWindow.quote_altered = False
self.txt.SetLabel("".join(MainWindow.base_copy))
self.txt.SetForegroundColour("BLACK")
self.sizer.Layout()
app = wx.App(False)
frame = MainWindow(None, "Cryptogrammar")
frame.Show()
app.MainLoop()
(I do, however, make a call in on_clear_all to set split_cryptoquote
to base_copy, but this shouldn't change base_copy.)
You've spotted your own problem:
MainWindow.split_cryptoquote = MainWindow.base_copy binds MainWindow.split_cryptoquote to the same object as MainWindow.base_copy, so when you modify one, you modify the other.
If you change the line to
MainWindow.split_cryptoquote = MainWindow.base_copy[:]
You will force python to create a new object (a copy of MainWindow.base_copy) , and this problem should not occur.
Edit: The line below:
MainWindow.split_buffer = MainWindow.base_copy also needs the same treatment, I think.
See this example:
>>> lista = [1,2]
>>> listb = lista
>>> listb.append(3)
>>> lista
[1, 2, 3]
>>> listb
[1, 2, 3]
>>> listc = lista[:]
>>> listc.append(4)
>>> listc
[1, 2, 3, 4]
>>> lista
[1, 2, 3]

What's the difference between these two functions in Tkinter?

Why are these two functions different?
def other_entry1(self, selection, row, el, var):
if selection == "Other":
var = StringVar()
el = Entry(self.frame1, textvariable=var)
el.grid(row=row, column=6)
#Calling it as part of an optionMenu
self.e33 = OptionMenu(self.frame1, self.ea_tf, *fixtures, command= lambda selection:self.other_entry1(selection,15, self.e33, self.ea_tf))
The other one:
def other_entry2(self, selection):
if selection == "Other":
self.ea_tf = StringVar()
self.e33 = Entry(self.frame1, textvariable=self.ea_tf)
self.e33.grid(row=15, column=6)
#Calling it in an optionMenu
self.e33 = OptionMenu(self.frame1, self.ea_tf, *fixtures, command=self.other_entry2)
I would like to be able to call the first function several times and just tell it what entry box to create instead of making several separate functions.
Edit: Isn't the second function just skipping the step of substituting in the arguments?
self.s33 is reference to OptionMenu
Second function overwrite self.e33 by reference to Entry and you can't use self.e33 to get access to OptionMenu.
First function copy reference from self.s33 to el then overwrites el by reference to Entry but you can still use self.s33 to get access to OptionMenu
See simple example using "Visual Execution" on PythonTutor.com:
Use link to open page with example, click "Visual Execution" and then you can use "Forward" button to see step by step how example works
function 1
function 2
You can use first function to create several Entry but you don't need to send self.e33 and self.ea_tf because function will not use it.
You get the same result as
def other_entry1(self, selection, row):
if selection == "Other":
var = StringVar()
Entry(self.frame1, textvariable=var).grid(row=row, column=6)
#Calling it as part of an optionMenu
self.e33 = OptionMenu(self.frame1, self.ea_tf, *fixtures, command=lambda selection:self.other_entry1(selection,15))
problem is with access to Entry or StringVar() to get value from Entry
self.all_vars = {} # dictionary
def other_entry1(self, selection, row):
if selection == "Other":
self.all_vars[row] = StringVar()
Entry(self.frame1, textvariable=self.all_vars[row]).grid(row=row, column=6)
#Calling it as part of an optionMenu
self.e33 = OptionMenu(self.frame1, self.ea_tf, *fixtures, command=lambda selection:self.other_entry1(selection,15))
# another place
row = 15
print "row:", row
print "value in Entry:", self.all_vars[row].get()
EDIT: working example
#!/usr/bin/env python
from Tkinter import *
class App():
def __init__(self, master):
self.master = master
self.all_entries = {} # empty dictionary
self.all_entries_vars = {} # empty dictionary
self.all_optionmenus = {} # empty dictionary
self.all_optionmenus_vars = {} # empty dictionary
fixtures = ["One", "Two", "Tree", "Other"]
# create 5 options menu
for i in range(5):
self.all_optionmenus_vars[i] = StringVar()
self.all_optionmenus_vars[i].set("One")
self.all_optionmenus[i] = OptionMenu(self.master, self.all_optionmenus_vars[i], *fixtures, command=lambda selection, col=i:self.addEntry(selection, col))
self.all_optionmenus[i].grid(row=1, column=i)
Button(master, text="Print OptionMenus Vars", command=self.printOptionMenus).grid(row=2, column=0, columnspan=5)
Button(master, text="Print Entries Vars", command=self.printEntries).grid(row=3, column=0, columnspan=5)
def run(self):
self.master.mainloop()
def addEntry(self, selection, col):
if selection == "Other":
# if Entry was created before
if col in self.all_entries:
# show existing Entry
self.all_entries[col].grid(row=0, column=col)
else:
# create new Entry
self.all_entries_vars[col] = StringVar()
self.all_entries[col] = Entry(self.master, textvariable=self.all_entries_vars[col])
self.all_entries[col].grid(row=0, column=col)
# if Entry was created before
elif col in self.all_entries:
# hide Entry
self.all_entries[col].grid_forget()
def printEntries(self):
print "-"*30
for key in self.all_entries_vars:
print "Entry #%d: %s" % ( key, self.all_entries_vars[key].get() )
def printOptionMenus(self):
print "-"*30
for key in self.all_optionmenus_vars:
print "OptionMenu #%d: %s" % ( key, self.all_optionmenus_vars[key].get() )
#----------------------------------------------------------------------
if __name__ == '__main__':
App(Tk()).run()