2

I started programming a simple GUI application in Python, using Tkinter library. Everything works fine but, to dynamically change any widget (for example a button from "login" to "logout", etc), I have to get the variable containing the widget object itself in the function from outside. I can do this in two ways:

  1. passing the widget as a argument;
  2. using global variables.

A simplified example:

1) Passing as argument:

def changeLabel(b):
    b.config(text='Logout')

btn1 = Button(f0,text="Login",width=15)
btn1.grid(row=1,column=2,rowspan=1,padx=10,ipadx=10)
changeLabel(btn1)

2) Or using a global variable:

def changeLabel():
    global btn1
    btn1.config(text='Logout')

btn1 = Button(f0,text="Login",width=15)
btn1.grid(row=1,column=2,rowspan=1,padx=10,ipadx=10)
changeLabel(btn1)

Now, I know that global variables should be avoided but passing every widget as argument through many functions, even in a simple application, it's a mess.

So, what's the best way to manipulate the Tkinter widgets at runtime? Can you suggest me the right way? Thank you

decadenza
  • 2,380
  • 3
  • 18
  • 31
  • 1
    Can't you just not have a `changeLabel` function at all, and do `btn1.config(text="Logout")` inline? Incidentally, the `global` statement isn't needed in approach #2, because you're not assigning anything to `btn1`. – Kevin Oct 31 '16 at 15:01
  • 1
    A third option is to use classes, where the widget is an attribute of the class. – Bryan Oakley Oct 31 '16 at 15:05
  • My example is voluntary simplified, in my application I need to: - hide a button and show another one - change text every click - hide/show frames - et cetera... – decadenza Oct 31 '16 at 15:07
  • @Kevin: I would say that calling a function is a best practice. Inlining code like that makes for a program that is harder to maintain over time. – Bryan Oakley Oct 31 '16 at 15:07
  • 2
    BTW, you're _already_ importing over 130 names into your global namespace because you do `from tkinter import *`. It's far better to do `import tkinter as tk`. – PM 2Ring Oct 31 '16 at 15:08

1 Answers1

5

The best way to manipulate tkinter widgets at runtime is to store those widgets as attributes of a class.

For example:

class Example(...):
    def create_widgets(self):
        ...
        self.btn1 = Button(...)
        ...
    def changeLabel(self):
        self.bt1.config(...)

For more information see Best way to structure a tkinter application

Community
  • 1
  • 1
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685