I have tried a lot of different things but nothing has worked so far.
I am trying to a Label(l1) increase or decrease by one each time the "+1"(b1) or "-1"(b2) button is pressed. But at the moment the Label just sits there and does nothing.
Here is the code in it's basic form without trying to update the label:
from tkinter import *
root = Tk()
p1 = 0
l1 = Label(root, textvariable = p1)
f1 = Frame(root)
b1 = Button(root, text = "+1", command = p1 + 1)
b2 = Button(root, text = "-1", command = p1 - 1)
l1.grid(row=0, column=0)
f1.grid(row=1, column=0)
b1.pack(side="top")
b2.pack(side="top")
root.mainloop()
There are several problems in your code:
command
option of a Button
takes a function and p1 +/- 1
is not a function.textvariable
option of a Label
takes a Tkinter variable, usually a StringVar
, but here an IntVar
is more appropriate.pack
and grid
in root
, which is not possible.To do what you want, you nedd to define two functions, one that increases the value of the IntVar
by 1 and the other that decreases it. Then, pass the functions to the command
option of the buttons and pass the IntVar
to the textvariable argument of the label:
import tkinter as tk
def increase():
p1.set(p1.get() + 1)
def decrease():
p1.set(p1.get() - 1)
root = tk.Tk()
p1 = tk.IntVar(root, 0)
l1 = tk.Label(root, textvariable=p1)
b1 = tk.Button(root, text="+1", command=increase)
b2 = tk.Button(root, text="-1", command=decrease)
l1.pack()
b1.pack()
b2.pack()
root.mainloop()
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments