I want to make a \"program\" that updates a label when you press a button and print out a variable, but with the code i have it does not work. Can someone help me out?
T
If you want to write it as a class, which has numerous advantages...
import Tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
self.x = tk.IntVar()
tk.Frame.__init__(self, master)
self.pack()
self.createWidgets()
def createWidgets(self):
tk.Label(self, textvariable=self.x).pack()
tk.Button(self, text='Click', command=self.increment).pack()
def increment(self):
self.x.set(self.x.get() + 1)
root = tk.Tk()
app = Application(master=root)
app.mainloop()
Instead of label_1.update()
(which doesn't do anything close to what you think it does), reconfigure the widget with label_1.config(text=x)
.
An alternative solution: using the textvariable
tag along with a Tkinter IntVar.
Example:
from Tkinter import *
root = Tk()
x = IntVar()
def test():
global x
x.set(x.get() + 1)
label_1 = Label(root, text=x.get(), textvariable = x)
button_1 = Button(root, text='Click', command=test)
button_1.grid(row=0, column=0)
label_1.grid(row=0, column=1)
root.mainloop()
*EDIT: Removed the label_1.update()
call as it is unnecessary