Home > Software design >  Button command doesn't updates my Label textvariable
Button command doesn't updates my Label textvariable

Time:01-28

I have this very easy program which I want to display one random line from a file each time I click on the Button.

Problem is a new line is display at startup of the program, but nothing happens when I click the button, can someone explain me why ?

from random import randrange
from tkinter import *

def entree():
    n=randrange(251)
    fs = open('lexique','r')
    liste = fs.readlines()
    return liste[n]


fen = Tk()
fen.title("lexique anglais politique")

defi = StringVar()
defi.set(entree())

lab = Label(fen, textvariable=defi).pack()

Button(fen, text='Beste Bat', command=entree).pack()

fen.mainloop() 

CodePudding user response:

As stated in one of the comments (by @matszwecja), your entree() function doesn't really do anything appart from returning a value.

Nothing in your code updates the actual label. Try something like this :

from random import randrange
from tkinter import *

def entree():
    n=randrange(251)
    fs = open('lexique','r')
    liste = fs.readlines()
    return liste[n]

def update_label():
    lab.config(text=entree())

fen = Tk()
fen.title("lexique anglais politique")


lab = Label(fen, text=entree())
lab.pack()

Button(fen, text='Beste Bat', command=update_label).pack()

fen.mainloop()

In this example, the entree() function is used to go get a line from your file, and the update_label() function is used to actually update the label.

Also, if you want to be able to update a label, you'll have to pack it after assigning it to a variable.


On a side note, it could be worth noting that hardcoding values that could change in the future is generally considered bad practice. In that regard, I think coding the entree() function this way might be a better idea :

def entree():
    fs = open('lexique','r')
    liste = fs.readlines()
    n=randrange(len(liste))
    return liste[n]

This way, if you ever add or remove lines to your "lexique" file, you will not have to change the code.

  •  Tags:  
  • Related