Increment everytime i press + button - python

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)

Related

Can I access Button information, which is not assigned to variable?

it's my first post here. I'm trying to create a 5x5 table with random numbers. The goal is that the user is supposed to click from the smallest to biggest number on the table, and once he clicked correct one it should be disabled. I don't want to attach each button to variable. I've created windows with random number, but now I'd like to create function which would check if the clicked number is the smallest, and if the answer is yes I have to change it's state to DISABLED. I been sitting on this for over 4 hours and I have no idea how to access clicked button information like 'text', and how can I disable it after user clicks on it.
Here's what I got so far, working on dat function.
from tkinter import *
import random
def click(z=None):
global o
Button(state=DISABLED)
o=Tk()
y=0
listrow=[4,3,2,1,0]
numbers=[]
spr=IntVar()
while len(numbers) < 25:
r = random.randint(0,999)
if r not in numbers:
numbers.append(r)
for i in range(1,26):
Button(o, text=str(numbers[i-1]), width=10).grid(row=listrow[i%5], column=y)
if i == 5:
y+=1
elif i == 10:
y+=1
elif i==15:
y+=1
elif i==20:
y+=1
else:
continue
o.bind_all('<Button-1>', click)
o.mainloop()
Consider integrating a class object with defined modules for building controls and the button click event. Specifically, on each button click check the minimum of the numbers list and disable corresponding button item by passing the index integer as parameter. See adjustment below.
Credit to #BrenBarn for the clever lambda solution lambda i=i in button command call:
from tkinter import *
import random
class NUMapp():
def __init__(self):
self.root = Tk()
self.buildControls()
self.root.mainloop()
def buildControls(self):
self.root.wm_title("Random Number Picker")
x = 0; y = 0
self.numbers = []; self.numbtn = []
while len(self.numbers) < 25:
r = random.randint(0,999)
if r not in self.numbers:
self.numbers.append(r)
for i in range(1,26):
self.numbtn.append(Button(self.root, text=str(self.numbers[i-1]), width=10,
command=lambda i=i:self.btnclick(i-1)))
self.numbtn[i-1].grid(row=x, column=y)
x+=1
if i % 5 == 0:
x = 0
y += 1
def btnclick(self, mynum):
currnum = int(self.numbtn[mynum].cget('text')) # CAPTURE BUTTON TEXT
if currnum == min(self.numbers):
self.numbtn[mynum].config(state="disabled") # DISABLE BUTTON
self.numbers.remove(currnum) # REMOVE FOR NEW MINIMUM
NUMapp()

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.

messagebox stops validation

I don't understand why a messagebox (or simpledialog) breaks the flow of the following code. The code basically validates an entry box in python 3.5. It checks that the field only contain numeric values and that it does't go over 9 digits long, the entry box can be empty though. The addition of a message to the user, after they OK it, allows the entry box to be more than 9 digits and accepts letter which of course I don't want it to do.
from tkinter import *
from tkinter import simpledialog
from tkinter import messagebox
root = Tk()
root.title("Zebra")
root.update_idletasks()
root.geometry("350x200+600+300")
root.config(bg="blue")
def okay(old,new): #,c,d,e,f,g,h):
try:
x = int(new)
except ValueError as ex:
if len(new) == 0:
return True
else:
return False
else:
if len(new) > 9:
messagebox.showerror("Error","Entry is too long")
# When messagebox is removed or commented out all is working ok
# but add below line and BINGO it works again :-)
txtNorm.config(validate='all', vcmd=vcmd)
# New line above as of 08/03/2016 brings validation back.
return False
elif len(new) <=9:
return True
finally:
if len(new) > 9:
return False
pass
def txtNormToggle(event): # When the user double clicks the field to enter or correct a number.
txtNorm.config(state="normal")
def txtNormFinished(a):
txtNorm.config(state="disabled")
root.focus()
vcmd=(root.register(okay),'%s','%P')
txtNorm = Entry(root)
txtNorm.grid(row=1, column=1,padx=(15,15),pady=(15,15), sticky=E+W)
txtNorm.insert(0,"123")
txtNorm.config(state="disabled", justify="center", validate='all', vcmd=vcmd)
txtNorm.bind('<Button>',txtNormToggle)
txtNorm.bind('<Control-z>',txtNormFinished)
txtNorm.bind('<Escape>',txtNormFinished)
txtNorm.bind('<Return>',txtNormFinished)
root.mainloop()
The above without the messagebox stops the user entering anything other than digits, which i want, with messagebox once OK is clicked the entry field allows more than 9 digits and other characters
edit: ok so I have created my own pop-up child window and the validation still goes out the window, suspect it is something to do with loss of focus from the main window killing the validation from the entry box. Any ideas please.
i have added validate back to the entry box in the (okay) function, it does't explain to me why the loss of validation occurs though. The code works now how i wanted

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)

Changing a variable through a button click; Python 3.4

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"

Categories