Changing a variable through a button click; Python 3.4 - python

Alright, so I have some code that I am using for a little clicker game I'm making for myself. I am trying to have the button with the original cost printed on it, and then, when I click the button, the cost updates on the button and the cost actually increases to the user. Take a look.
These are all of my variables.
click = 0
mult = 1
dcp1 = 0
autoclickers = 0
mines = 0
grandmas = 0
doubleclickcost = 5
autoclickercost = 7
minecost = 10
grandmacost = 15
costmultiplyer = 1.3
Btw I am just taking out the code in question. This is the code that handles the grandma cost.
purchaseGrandmaButton = Button(master, text="Purchase Grandma - " + str(grandmacost) + " Clicks", command = purchaseGrandmaCommand)
purchaseGrandmaButton.pack()
So what I am trying to do is have the button update the amount that the button displays the cost of the grandmas.http://puu.sh/hOWdf/0970e92276.png <- Before I buy a grandma. http://puu.sh/hOWfy/6dad5b94bb.png <- After I buy a grandma. The number/cost on the button doesn't change, and I want it to, but I don't know how.

You can reconfigure the button's text each time it's clicked:
grandmacost = 15
def purchaseGrandmaCommand():
global grandmacost
grandmacost +=15
global purchaseGrandmaButton
purchaseGrandmaButton.config(text="Purchase Grandma - " + str(grandmacost) + " Clicks"

Related

counting code giving me 0 instead of a value

this is my code:
from threading import Timer
timeout = 5
t = Timer(timeout, print, ['Sorry, times up'])
t.start()
count_push1 = + 1
print("Please push the button to count up.You have 5 seconds.")
while True:
if bool(push_button1.read()):
press_count = + 1
print(press_count)
sleep(0.2)
break
else:
print('You pressed', press_count, 'times.')
break
break
I want the user to have 5 seconds.In that 5 seconds, the user will click a button, and timer will reset to 5 seconds.If button is not clicked in 5 seconds,it shows the total number of times user pressed the button.I tried but when I run the code,the code automatically ends.Someone help please
You have the order of the operators wrong. In your while loop, you need to change the counter to count_push1 += 1
At the top where you define the variable as being 1, I would remove the the + for readability.
Edit: count_push1 += 1 is short for count_push1 = count_push1 + 1

Is it possible to use a variable then later redefine it?

I´m making a project for school and it is a dice game. This snippet of my code is like a catch 22.
I need to define a variable otherwise it flags, so I do this but then every time the button is run it changes the value to zero instead of increasing it.
if Rollnop1 == 0 :
Userscore1 = Randomnumber
print ("User 1 ",Userscore1 )
Rollnop1 = Rollnop1+1 #But this changes it so it will go to the next players roll, every
#time the button is pressed it changes the variable back to 0
def gamerun():
global Player
global usernamestr
global passwordstr
global usernamestr2
global passwordstr2
Rollnop1 = 0
def roll2():
Rollnop2 = 0
Randomnumber = random.randint(2,12)
print ("Console: Random Number 2 = ",Randomnumber)
if Rollnop2 == 0 :
Userscore2 = Randomnumber
print ("User 2 ",Userscore2 )
def roll1():
Rollnop1 = 0 #Need to define this here otherwise It wont work
Randomnumber = random.randint(2,12)
print ("Console: Random Number = ",Randomnumber)
if Rollnop1 == 0 :
Userscore1 = Randomnumber
print ("User 1 ",Userscore1 )
Rollnop1 = Rollnop1+1 #But this changes it so it will go to the next players roll, every
#time the button is pressed it changes the variable back to 0
else:
roll2()
actdicegame = Tk()
gamerunl0 = Label(actdicegame, text = usernamestr, fg = "black")
gamerunl0.pack()
gamerunl1 = Label(actdicegame, text = "Roll The Dice", fg = "black")
gamerunl1.pack()
gamerunb1 = Button(actdicegame, text="ROLL",fg="Black", command=roll1)#Register Butto
gamerunb1.pack()
actdicegame.geometry("350x500")
print ("Console: GUI RUNNING 1")
actdicegame.mainloop()
snippet https://pastebin.com/FSWwBGpA
Use an option where you provide the player as part of the roll, that way you say which player is playing at any given time. The function below plays for the provided player and returns who is playing next
def roll(Rollnop=0):
UserScore = random.randint(2,12)
print ("Console: Random Number 2 = ", UserScore)
if Rollnop == 0 :
print ("User 1 ", UserScore)
return 1
else:
print ("User 2 ", UserScore)
return 0
This could answer your question: nested function change variable in an outside function not working. Basically you need to assign Rollnop1 = 0 and Rollnop2 = 0 in gamerun and declare them as nonlocal inside roll1 & roll2 before attempting to change their value.
– DarrylG Thank You so much and to everyone else who helped.
More here
nested function change variable in an outside function not working

Increment everytime i press + button

I'm working on this Incrementor Decrementor program .. where First i enter a number and as i press + the entered number is incremented by 1 and decrements when i press - ... The problem is the value is getting incremented or decremented only once.
from tkinter import *
#******* Functions code ********
def add(event):
a=float(enter.get())
b=a+1
labelresult=Label(root,text="Result : %2f"%b).grid(row=3,column=1)
return
def sub(event):
a=float(enter.get())
b=a-1
labelresult=Label(root,text="Result : %2f"%b).grid(row=3,column=1)
return
#******* GUI code***********
root=Tk()
root.geometry('250x250')
root.title('Incrementor or Decrementor')
enter=IntVar()
label=Label(root,text="Skz.inc",bg='skyblue',fg='red').grid(row=0,column=1)
label=Label(root,text="enter a number").grid(row=1)
entry_1=Entry(root,textvariable=enter).grid(row=1,column=1)
button1=Button(root,text='+')
button1.grid(row=2,column=0)
button1.bind('<Button-1>',add)
button2=Button(root,text='-')
button2.grid(row=2,column=3)
button2.bind('<Button-1>',sub)
root.mainloop()
So the value which i entered should be increment or decrement each time i press either + or - button .
Example - when i enter 9 and press + the result should be 10 (works in my program) . Again on pressing + button the result should be 11 which is not the case in my code.
Help me out guys .. do modify and send me back the code.
Thanks
Each time you press + or - the function reads the value in the entry. You will have to update the value in the entry for every add or sub.
def add(event):
a=float(enter.get())
b=a+1
labelresult.config(text="Result : %2f"%b) # Update labelresult instead of
# creating a new label every time
enter.set(b) # Set entry to the new value
return
You will have to create labelresult in the GUI code:
labelresult = Label(root)
labelresult.grid(row=3,column=1)

How do you update a variable when using a button in tkinter?

I am writing a simple game where when the 'calculate' button is clicked, it performs the necessary calculations and displays a messagebox to the user. The user can then keep playing. However, the variable that keeps track of the money the user has, 'starting', does not update each time the button is clicked and it uses the starting value of 1000. How can I have it update? Thank you!
starting = 1000
#calculation procedure
def calculate(starting):
dice1 = random.randrange(1,7)
get_bet_entry=float(bet_entry.get())
get_roll_entry = float(roll_entry.get())
if dice1 == get_roll_entry:
starting = starting + get_bet_entry
messagebox.showinfo("Answer","You won! Your new total is $" + str(starting))
return(starting)
else:
starting = starting - get_bet_entry
messagebox.showinfo("Answer","You are wrong, the number was " + str(dice1) + '. You have $' + str(starting))
return(starting)
#designing bet button
B2 = Button(root,text = "Bet", padx=50, command = lambda: calculate(starting))
You can declare starting as a global variable inside your calculate function, so it gets updated in the global scope.
You could also make "starting" part of a mutable object if you want to avoid globals.
You shouldn't return a value from button's callback since it doesn't have a variable to return.
You can either use global to update your variable within a method or use IntVar(). I would suggest using IntVar().
starting = IntVar(root)
starting.set(1000)
def calculate():
#calculations
starting.set(calculation_result)
messagebox.showinfo("Answer","You won! Your new total is $" + str(starting.get()))
B2 = Button(......, command = calculate)
If you really want to use global,
starting = 1000
def calculate():
global starting
#calculations
starting = calculation_result
B2 = Button(......, command = calculate)
Note that in both approaches, you don't need to pass starting as parameter to your method.

Changing property of a QLE in python

I'm currently having an issue with a QLE that I created. I would like the qle to take a value, turn it into a float and then increase or decrease a label value depending on if the value is positive or negative. The only problem is is that every time I type something into the qle it will start adding that value to the label before I'm done typing. For example: I type in "4" into the qle that works but once I type in "4." anything it will read it as 4 two times so the label will be changed to 8. Maybe there's a way so that when I press a button it will increase or decrease but only after I press the button?
I added code for a button I created and maybe it would be easier to link that with the qle. Many thanks!
#this creates the increase button for cam1 focus
self.btnCam1IncreaseFocus = QtGui.QPushButton("+",self)
self.btnCam1IncreaseFocus.clicked.connect(self.cam1IncreaseFocus)
self.btnCam1IncreaseFocus.resize(25,25)
self.btnCam1IncreaseFocus.move(75,100)
#This creates a textbox or QLE for a custom tweak value for cam1 focus
self.qleTextBoxCam1Focus = QtGui.QLineEdit(self)
self.qleTextBoxCam1Focus.resize(25,25)
self.qleTextBoxCam1Focus.move(40,100)
self.qleTextBoxCam1Focus.textChanged[str].connect(self.qleCam1Focus)
def cam1IncreaseFocus(self):
text = self.lblCam1Focus.text()
n = float(text)
n = n + 1
self.lblCam1Focus.setText(str(n))
def qleCam1Focus(self):
text = self.qleTextBoxCam1Focus.text()
if text == "":
text = "0.0"
if str(text).isalpha() == False:
n = float(text)
textLabel = self.lblCam1Focus.text()
if textLabel == "":
textLabel = "0.0"
y = float(textLabel)
result = n + y
if result <= 0.0:
result = 0.0
self.lblCam1Focus.setText(str(result))
Instead of textChanged, use the editingFinished signal, which will only fire when return/enter is pressed, or when the line-edit loses focus:
self.qleTextBoxCam1Focus.editingFinished.connect(self.qleCam1Focus)

Categories