frevi 3
frevi 3

Reputation: 1

Tkinker button function not working as desired

I've just started my first attempts in coding lately and wanted to do this little app for a challenge, basically it's meant to

  1. Generate a hex colour on click
  2. Show it as a value and display a real color.

I can generate the value, show it and apply a colour, but only at launch and cannot get the button working (ideally you could spam it as long as you want generating new results.)

import random as rd
import tkinter as tk

values = ["0", "1", "2", "3","4", "5","6", "7","8", "9","A", "B","C", "D","E", "F"]

root = tk.Tk()

def generate():
    rd.shuffle(values)
    return (f"#{values[0]}{values[1]}{values[2]}{values[3]}{values[4]}{values[5]}")


valTest = generate()
canvas = tk.Canvas(root, height=800, width=600)
canvas.pack()
canvas.update()
kolor = tk.Label(root, text=generate())
kolor.pack()

canvas['bg'] = generate()

Generuj = tk.Button(root, text="Generuj", height=80, width=60, bg="white", fg="black", 
                    command=generate)
Generuj.pack()
Generuj.invoke()
canvas.update_idletasks()

root.mainloop()

I don't know what to google at this point.

Upvotes: 0

Views: 46

Answers (2)

acw1668
acw1668

Reputation: 46688

You need to update canvas and kolor inside generate(). Also, simply use random.randint() instead of random.shuffle():

import random as rd
import tkinter as tk

root = tk.Tk()

def generate():
    color = rd.randint(0, 0xffffff)
    hex_color = f"#{color:06x}"
    canvas.config(bg=hex_color)
    kolor.config(text=hex_color)

canvas = tk.Canvas(root, height=800, width=600)
canvas.pack()

kolor = tk.Label(root)
kolor.pack()

Generuj = tk.Button(root, text="Generuj", height=8, width=60, bg="white", fg="black", command=generate)
Generuj.pack()

generate() # show first random color

root.mainloop()

Upvotes: 0

Lukas Schmid
Lukas Schmid

Reputation: 1960

Your button only generates a value, but never assigns it.

Make a new function for assignment like this:

def updatebg():
    canvas['bg'] = generate()

Upvotes: 1

Related Questions