Tkinter gui not displaying in python

Question:

I am making this app where it will display the name of a random friend from a list(the list is in the code). But nothing is displaying in the tkinter window when I run the app except the title

The code:

# -*- coding: utf-8 -*-
"""
Created on Sat Nov 12 11:42:32 2022

@author: Techsmartt
"""
from tkinter import *
import random

root = Tk()
root.title("Luck Friend Wheel")
root.geometry("400x400")

list = ["James", "Isabella", "Sophia", "Olivia", "Peter"]
print(list)

def randomnumber():
    random_no = random.randint(0, 4)
    print(random_no)
    random_lucky_friend = list[random_no]
    print("Your lucky friend is: " + random_lucky_friend)
    
    btn = Button(root)
    btn = Button(root, text= "Who is your lucky friend?", command = randomnumber)
    btn.place(relx=0.4,rely=0.5, anchor=CENTER)

root.mainloop()

btw I’m using anaconda spyder

Asked By: Tech Smartt

||

Answers:

You need to move your GUI code outside the randomnumber function, otherwise the widget is never created:

from tkinter import *
import random

root = Tk()
root.title("Luck Friend Wheel")
root.geometry("400x400")

list = ["James", "Isabella", "Sophia", "Olivia", "Peter"]

def randomnumber():
    random_no = random.randint(0, 4)
    random_lucky_friend = list[random_no]
    print("Your lucky friend is: " + random_lucky_friend)
    
btn = Button(root, text= "Who is your lucky friend?", command = randomnumber)
btn.place(relx=0.4,rely=0.5, anchor=CENTER)

root.mainloop()
Answered By: Marin Nagy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.