I'm having trouble removing a widgets with a label once it's added
Here's the relevant piece of code:
logi= True
if data == []:
logn =Label(text= "Incorrect Username",color=(190,0,0,1),
pos_hint={"right":1.035,"top":1.14})
self.add_widget(logn)
logu =Label(text= "Incorrect Password",color=(190,0,0,1),
pos_hint={"right":1.035,"top":1.04})
self.add_widget(logu)
logi= False
if logi == True:
textinput.text=''
textinput2.text=''
if 'logn' in locals() and 'logu' in locals() :
self.remove_widget(logn)
self.remove_widget(logu)
once the widgets have been added I can't seem to remove them, if i remove the if 'logn' in locals() and 'logu' in locals() :statement I get an error "Local variable referenced before assignment " every time I test this without the above mentioned if statment I make sure the widgets have been added
I assume you are entering this method twice (1st data==[] 2nd time data=[...]). So You should keep your variables at hand (put them on the instance - self)
logi= True
if data == []:
self.logn =Label(text= "Incorrect Username",color=(190,0,0,1),
pos_hint={"right":1.035,"top":1.14})
self.add_widget(self.logn)
self.logu =Label(text= "Incorrect Password",color=(190,0,0,1),
pos_hint={"right":1.035,"top":1.04})
self.add_widget(self.logu)
logi= False
if logi == True:
textinput.text=''
textinput2.text=''
if hasattr(self, 'logn'): #check that we put something here before...
self.remove_widget(self.logn)
self.remove_widget(self.logu)
Note all the places I've added self ...
Related
I have a simpler controller method that does the following:
def updateName(){
def idUser = params.id
User changeUser = User.get(idUser)
changeUser.name = "newname"
changeUser.save(flush: true)
}
And the following Spock test:
def "updateName should edit user and save it"(){
given: "the id of the user"
User currentUser = new User([name: "hector" , age: 12]).save(flush: true)
params.id = User.last().id
when: "the updateName method is called"
controller.updateName()
then: "name should have change it and save has to be called just one time"
assert currentUser.name == "newname" // Success
1 * _.save() // Too few invocations, 0.
}
I have seen all the related questions in SO about this topic, and people suggest using Mocks and Spy, but I don't really see why should I be using them and anyway I didn't get them to work for me, I tried to create a User mock and change my cardinality assert to:
1 * userMock.save()
But it didn't work for me... can I have some help with this?
To make it work, I create a GroovyMock that allows me to access to static functions such as save.
def "updateName should edit user and save it"(){
given: "the id of the user"
params.id = 1
User mockUser = GroovyMock(User, global: true)
when: "the updateName method is called"
controller.updateName()
then: "set Name and save has to be called just one time"
1 * User.get(1) >> mockUser
1 * mockUser.setName("newname")
1 * mockUser.save()
} //All test passed!
Not sure if it's the best way to do it, but it works for me! I'll leave the question in case someone offers a better solution, or throws some good information about this
I have this function I have built and it seems like I am missing something very minor here. This loop will not call for some reason. Indentation looks good and I am not getting any errors in my output, but the data is not being updated which you can see by the debug print statement I made not showing in the terminal.
Below is the function I am speaking of:
def updatefield(layer, prev_data):
print("DEUBG:: UPDATE FIELD")
fname, ftype, fdict = field_attr(prev_data)[0], field_attr(prev_data)[1], field_attr(prev_data)[2]
arcpy.AddField_management(
in_table=layer,
field_name=fname,
field_type=ftype,
field_is_nullable="NULLABLE"
)
# Use UpdateCursor to expedite the copy of the data to the new field.
with arcpy.da.UpdateCursor(layer, [prev_data, fname, "OID#"]) as uc:
print("DEUBG:: UPDATE CURSOR: {}".format(layer))
for record in uc:
print("\tDEBUG:: record: {}".format(record)) # THIS NEVER GETS CALLED
if record[0] in fdict.keys():
record[1] = fdict[record[0]]
else:
if layer == fms_conduit:
record[1] = None
# Can't recall if you can have empty keys...These also pretty much only apply to fiber.
elif prev_data == "CATEGORY" and record[0] == "":
record[1] = "OTH"
elif prev_data == "CABLECAPACITY" and (record[0] in ('', ' ', None)):
record[1] = 0
elif prev_data == "CABLECAPACITY":
record[1] = int(record[0])
else:
record[1] = ""
print("\nDEBUG:: OID: {}\tPrevField: {}\t NewFieldName: {}\tNewFieldValue: {}".format(
record[2], prev_data, fname, record[1])
)
uc.updateRow(record)
And here is the output:
The final few debug print statements are from another function but I should be getting that record printed. Again, probably something silly but I can't seem to get it.
Thank you for your time.
Turns out the data that was delivered to me was truncated at some point. The update cursor was empty and therefore nothing was being translated.
I am trying to code a simple hangman game in python with a gui using tkinter. I have the gui frame set up with a user entry. The problem is when I enter a letter then run the code by pressing the play button it runs the letter through the code until the code runs out of lives (10 times). How can i improve my code so a letter is only run through once then a new letter can be input to guess again?
thank you
from numpy import*
from Tkinter import*
#set up gui frame
win=Tk() #create window assigned to variable win
welc=Label(win,text="Welcome to Hangman!").grid(row=0)
inst=Message(win,text="instructions: To play start by guessing a letter in the secret word. if the letter is in the word it will fill in a blank if not you lose a life. Continue guessing untill you have guessed the secret word.").grid(row=1)
guess_text=Label(win,text="Enter a letter or Word").grid(row=2)
blank_text=Label(win,text="Secret Word").grid(row=3)
lives_text=Label(win,text="Lives Remaining").grid(row=4)
e=Entry(win)
e.grid(row=2,column=1)
#library of secret words
lib=['hanakah','christmas','holly','thanksgiving','reigndeer','family','presents','santa','kwanza', 'chocolate', 'cheesecake']
n=len(lib)
#randomly pick secret word
inx=random.randint(1,n)
secret=lib[inx]
#set up game
lives_remaining=10
guessed_letters=''
#define function to play game
def play():
word=secret
while True:
guess=get_guess(word)
print guess
print type(guess)
if process_guess(guess,word):
Label(win,text="You Win!").grid(row=6)
break
if lives_remaining==0:
Label(win,text="You Lose!").grid(row=6)
Label(win,text="The secret word was: "+word).grid(row=7)
break
Button(win,text=("Play"),command=play).grid(row=5,column=0)
def get_guess(word):
blanks(word)
guess=e.get()
return guess
#diplay guessed letter in postion of word
def blanks(word):
Label(win,text=lives_remaining).grid(row=4,column=1)
display_word=''
for letter in word:
if guessed_letters.find(letter)> -1:
#LETTER found
display_word=display_word+letter
else:
#letter not found
display_word=display_word+'-'
Label(win,text=display_word).grid(row=3,column=1)
def process_guess(guess,word):
if len(guess)>1 and len(guess)==len(word):
return whole_word_guess(guess, word)
else:
return single_letter_guess(guess, word)
def whole_word_guess(guess, word):
if guess.lower() == word.lower():
return True
else:
lives_remaining=lives_remaining+(-1)
return False
def single_letter_guess(guess, word):
global guessed_letters
global lives_remaining
if word.find(guess) == -1:
# letter guess was incorrect
lives_remaining = lives_remaining+(-1)
guessed_letters = guessed_letters + guess.lower()
if all_letters_guessed(word):
return True
return False
def all_letters_guessed(word):
for letter in word:
if guessed_letters.find(letter.lower()) == -1:
return False
return True
mainloop()
I think I understand now.
The get_guess function is always pulling whatever info is in the e Entry, it's not waiting for the value of e to change.
A simple fix without creating listeners would be to create a new global variable called last_guess which can be initialized to '' and then passsed to get_guess as a 2nd arg to check if the guess has changed:
def get_guess(word, last_guess):
blanks(word)
guess=e.get()
#If the guess has not changed ret false
if guess == last_guess:
return False
#If the guess has changed update the last_guess
else:
last_guess = guess
return guess
And then in the main While loop:
while True:
guess=get_guess(word)
print guess
print type(guess)
if not guess: #<-- If the get_guess returned False
continue #<-- Just go on to on to the next iteration of the loop w/out updating lives etc
if process_guess(guess,word):
Label(win,text="You Win!").grid(row=6)
break
if lives_remaining==0:
Label(win,text="You Lose!").grid(row=6)
Label(win,text="The secret word was: "+word).grid(row=7)
break
I haven't run this code so it might have errors, but I think the general idea will work
So I have an object with a set of attributes that are boolean flags that mark whether something has been published or not. There are several different formats it can be published to: published_to_web, published_to_email, published_to_pdf, etc. Rather than having a separate method to reset each format, I thought I would simply use one method, and set the attribute with a variable sent when the pertinent button (web, email, pdf, etc.) was clicked on. So for example a button calls the method and params[:format] = 'web', so I want to set the object's 'publish_to_web' attribute to false:
#bulletin.update_attributes( "published_to_#{params[:format]}", false)
but I can't get it to work. Seems like it should be simple in RoR but I can't seem to get the right juju. I've tried:
#bulletin.update_attributes( "published_to_#{params[:format]}".to_sym, false )
#bulletin.update_attributes( "published_to_#{params[:format]}", false )
#bulletin.update_attributes( "published_to_#{params[:format]}: false" )
#bulletin.update_attributes( ":published_to_#{params[:format]}" => false)
... what's the secret sauce?
#bulletin.update_attributes( "published_to_#{params[:format]}" => false)
I'm trying to make a conditional statement based on whether a checkbox is checked or not. I've tried something like the following, but it always returns as true.
self.folderactive = QtGui.QCheckBox(self.folders)
self.folderactive.setGeometry(QtCore.QRect(50, 390, 71, 21))
self.folderactive.setObjectName(_fromUtf8("folderactive"))
if self.folderactive.isChecked:
folders.createDir('Desktop')
print "pass"
elif not self.folderactive.isChecked:
folders.deleteDir('Desktop')
print "nopass"
Is there a way to get a bool value of whether a checkbox is checked or not?
self.folderactive.isChecked isn't a boolean, it's a method - which, in a boolean context, will always evaluate to True. If you want the state of the checkbox, just invoke the method:
if self.folderactive.isChecked():
...
else:
...
x = self.folderactive.isChecked()
x will be True or Falseāa Boolean value.
(It's the brackets at the end that make the difference.)