0

Pretty basic stuff. I had this code:

from tkinter import *
import secrets

def stuff():
    stuff = ["study math",
             "Phone", "social",
             "study python","tv",
             "exercise"]
    print(secrets.choice(stuff))

window = Tk()

button = Button(window,
                text="click me",
                command=stuff,
                font=("Comic Sans", 40),
                fg="#00FF00",
                bg="black",
                activeforeground="#00FF00",
                activebackground="black")

button.grid()

But that only prints the listed word on the terminal. I want to print the word on the GUI as a Label. I'm trying stuff like this,

def stuff():
    stuff = ["study math",
             "Phone", "social",
             "study python","tv",
             "exercise"]
    Label(window, secrets.choice(stuff)).grid(row=1)

Butt.. cant quite figure it out. Can anyone point me in the right direction?

  • Should be `Label(window, text=secrets.choice(stuff)).grid(row=1)` – acw1668 Aug 01 '22 at 23:15
  • You can use a StringVar with Label. See https://stackoverflow.com/questions/2603169/update-tkinter-label-from-variable for example. – Tim Aug 01 '22 at 23:24

1 Answers1

0

You need to use the text option to set the text of a Label widget. Also suggest to create the label once outside stuff() function.

from tkinter import *
import secrets

def stuff():
    stuff = ["study math",
             "Phone", "social",
             "study python","tv",
             "exercise"]
    # update the label with the random choice
    choice.config(text=secrets.choice(stuff))


window = Tk()

button = Button(window,
                text="click me",
                command=stuff,
                font=("Comic Sans", 40),
                fg="#00FF00",
                bg="black",
                activeforeground="#00FF00",
                activebackground="black")

button.grid(row=0, column=0) # better to specify row and column

# label to show the random message
choice = Label(window)
choice.grid(row=1, column=0)

window.mainloop()
acw1668
  • 40,144
  • 5
  • 22
  • 34