Adding 1 to number - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Adding 1 to number (/thread-3110.html) |
Adding 1 to number - JohnNo - Apr-29-2017 I cant find anwser anywhere for this question. I have a number and when i click a button i want that number + 1 and so on so like this. from tkinter import * root = Tk() zeroo = 0 def add(): zeroo = 0 for zeroo in range(900): zeroo = zeroo + 1 print(zeroo) x = Button(root,text="Do it!", command=add) x.pack() x.mainloop()But this code only prints 900 and what I want is this When you click the button it prints 1 When you click again it prints 2 and so on but i dont know how RE: Adding 1 to number - wavic - Apr-29-2017 I don't know Tkinter at all but try this from tkinter import * root = Tk() zeroo = 0 def add(zeroo): if zeroo <= 900: return zero + 1 x = Button(root,text="Do it!", command=add) y = Label(root, text=zeroo) x.pack() x.mainloop() RE: Adding 1 to number - JohnNo - Apr-29-2017 Well that just prints nothing #2 well i edited the code no error but it prints nothing from tkinter import * root = Tk() zeroo = 0 def add(): if zeroo <= 900: return zeroo + 1 print(zeroo) x = Button(root,text="Do it!", command=add) y = Label(root, text=zeroo) x.pack() x.mainloop() RE: Adding 1 to number - snippsat - Apr-29-2017 You can use IntVar() which has a get method.>>> import tkinter >>> root = tkinter.Tk() >>> counter = tkinter.IntVar() >>> counter.get() + 1 1 import tkinter root = tkinter.Tk() root.geometry("200x100") counter = tkinter.IntVar() def add(): counter.set(counter.get() + 1) tkinter.Label(root, textvariable=counter).pack() tkinter.Button(root, text="Do it!", command=add, fg="dark green").pack() root.mainloop()Do no use from tkinter import * even if this is common in many Tkinter tutorials.
RE: Adding 1 to number - nilamo - Apr-29-2017 (Apr-29-2017, 01:14 PM)JohnNo Wrote: #2 well i edited the code Of coarse it prints nothing, you return from the function before ever trying to print anything. Aside from that, though, try to avoid global variables. It might be a hassle at first, but it'll make your life much better later on :) All the cool kids have posted code, so here's some from me, too: >>> import tkinter as tk >>> class Counter(object): ... def __init__(self, start: int = 0): ... self.value = start ... def add(self) -> int: ... if self.value < 900: ... self.value += 1 ... print(self.value) ... return self.value ... >>> clicks = Counter() >>> root = tk.Tk() >>> tk.Button(root, text="click me!", command=clicks.add).pack() >>> root.mainloop() 1 2 3 4 5 6 >>> RE: Adding 1 to number - Turry - Apr-29-2017 You get 900 because you made the script go in a range from 0 to 899 with x Remove that ****. |