Update a label in Tkinter when pressing a button

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?

Thanks in advance!

from Tkinter import * root = Tk() x = 0 def test(): global x x += 1 label_1.update() label_1 = Label(root, text=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()

--------------Solutions-------------

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

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()

Category:python Time:2018-12-04 Views:0
Tags: python tkinter

Related post

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 2.368 (s). 14 q(s)