Question

Newish to programming and just learning Tkinter. Wrote this based on an example in Alan Gauld's online Tutorial. I am expecting a random number between 1 and 10 to be put into the label, but I am getting what seems to a be a random number between 40million and 50 million, followed by "getRandomNumber". The code:

import random
from tkinter import *

class randomNumberApp:
    def __init__(self, parent=0):
        self.mainWindow = Frame(parent)
        self.fTop = Frame(self.mainWindow)
        self.fTop.pack(fill="both")
        self.lInfo = Label(self.fTop, text="Your number is:")
        self.lInfo.pack(side="left")
        self.lScore = Label(self.fTop, text=self.getRandomNumber)
        self.lScore.pack(side="left")
        self.mainWindow.pack(fill="both")

    def getRandomNumber():
        ability = random.randint(1,10)
        return ability

# top level
top = Tk()
app = randomNumberApp(top)
top.mainloop()

Any help would be great

Was it helpful?

Solution 2

The problem is that you are creating a label, and for it's value you are giving a function. You don't want to use a function as the text of the label, you want to call the function and use what the function returns for the label.

Instead of this:

self.lScore = Label(self.fTop, text=self.getRandomNumber)

... you need to do this:

self.lScore = Label(self.fTop, text=self.getRandomNumber())

Also, if getRandomNumber is to be a method, you need to defined it to have the parameter self, as in the following example:

class randomNumberApp:
    ...
    def getRandomNumber(self):
        ...

OTHER TIPS

This works:

Changed to "text=self.getRandomNumber()" and indented "def getRandomNumber(self):" because it is more like the code from the OP.

import random
from tkinter import *

class randomNumberApp:
    def __init__(self, parent=0):
        self.mainWindow = Frame(parent)
        self.fTop = Frame(self.mainWindow)
        self.fTop.pack(fill="both")
        self.lInfo = Label(self.fTop, text="Your number is:")
        self.lInfo.pack(side="left")
        self.lScore = Label(self.fTop, text=self.getRandomNumber())
        self.lScore.pack(side="left")
        self.mainWindow.pack(fill="both")

    def getRandomNumber(self):
        ability = str(random.randint(1,10))
        return ability

# top level
top = Tk()
app = randomNumberApp(top)
top.mainloop()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top