Reputation:
I have been trying to make a simple dice rolling GUI where you press a button and a dice rolls and gives you the output in a label. When I run my code I get the error that "diceOutput" is not defined. Here is my code:
from tkinter import *
import random
window = Tk()
window.title("Dice")
def rollDice():
diceOutput = str(random.randint(1,6))
return diceOutput
roll = Button(window, text="Roll", command=rollDice)
output = Label(window, textvariable=diceOutput)
window.mainloop()
Upvotes: 0
Views: 866
Reputation: 142641
As Reblochon Masque showed you don't need textvariable=
to change text in Label
... but if you use textvariable=
then you have to use class StringVar()
/ IntVar()
/ etc.
and you have to use variable.set()
to change value in StringVar()
/ IntVar()
/ etc.
and it will change text in Label
(BTW: to get value you have to use variable.get()
)
import tkinter as tk
import random
# --- functions ---
def roll_dice():
dice_output.set( random.randint(1, 6) )
# --- main ---
window = tk.Tk()
window.title("Dice")
roll = tk.Button(window, text="Roll", command=roll_dice)
roll.pack()
dice_output = tk.StringVar()
output = tk.Label(window, textvariable=dice_output)
output.pack()
window.mainloop()
Upvotes: 0
Reputation: 36682
You need to include the label and button in the window, using a layout manager. Here I used .pack()
You do not need the global variable diceOutput
.
Then you need to assign the new dice roll to the text label, once the button has been clicked:
from tkinter import *
import random
window = Tk()
window.title("Dice")
def rollDice():
dice_roll_result = str(random.randint(1,6))
outlbl['text'] = dice_roll_result
roll = Button(window, text="Roll", command=rollDice)
roll.pack()
outlbl = Label(window, text='')
outlbl.pack()
window.mainloop()
Upvotes: 1