Home > database >  Tkinter gui not displaying in python
Tkinter gui not displaying in python

Time:11-12

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

CodePudding user response:

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