1

I've got a program that counts clicks of a button and displays them on a label. Instead of just showing the number, how can I add "Number of clicks: " before the value displayed? Preferably within the Label's widget arguments/options where textvariable=Total is defined.

Total = IntVar()

def Clicked():
    Total.set(Total.get() + 1)

total = Label(root, textvariable=Total).pack()
click = Button(root, command=Clicked).pack()

2 Answers2

1

tkinter requires that you use its own variable types for textvariable, so I would use a StringVar as your textvariable (you can update the text property of some items directly, but different tkinter objects may have different methods for doing this, and it can get confusing). Here's how you can update a StringVar to show your counts.

root = tk.Tk()
tk.IntVar(value='1')
sv = tk.StringVar()
sv.set('clicks = ' + str(iv.get()))

>>> sv.get()
'clicks = 1'
BlivetWidget
  • 10,543
  • 1
  • 14
  • 23
  • It's a bit misleading to say that tkinter _requires_ you to use it's own variable types. They are only required in a very few specific instances, such as with radiobuttons and checkbuttons. – Bryan Oakley Nov 02 '15 at 18:34
  • @BryanOakley, fair enough, though it does require them for the textvariable. Like I said, there are ways around it, but I get a feeling of clunkiness since the various types of tkinter objects can have different ways of updating their text, whereas if you set them to a StringVar (for example) you can update a Label and an Entry in the same way. I'll edit my post to clarify. – BlivetWidget Nov 02 '15 at 18:52
1

Use separate variables to keep track of the number of clicks, and the string that represents the number of clicks.

from Tkinter import *


def Clicked():
    global amount
    amount += 1
    Total.set("Number of clicks: {}".format(amount))

root = Tk()
Total = StringVar()
amount = 0

Label(root, textvariable=Total).pack()
Button(root, command=Clicked).pack()
root.mainloop()

Incidentally, never pack a widget and assign it to something on the same line - your variable will always be None. See Tkinter: AttributeError: NoneType object has no attribute get for more information.

Community
  • 1
  • 1
Kevin
  • 74,910
  • 12
  • 133
  • 166