PDA

View Full Version : (PyQt4) How to update a label with a random value from a list



4thLaw
1st February 2017, 00:25
Basically, I'm making a program that relies on random generation from lists. The first generation works fine but I want it so that when I press the "random" button, the field is automatically updated with another name. I'm new to PyQt (a few days) and Python in general so a little help would be appreciated :)



def random_hero(self):
hero_dict = ["Adagio", "Alpha", "Ardan", "Baron", "Blackfeather", "Catherine", "Celeste", "Flicker", \
"Fortress", "Glaive", "Gwen", "Idris", "Joule", "Kestrel", "Koshka", "Krul", "Lance", "Lyra", "Ozo", "Petal", \
"Phinn", "Reim", "Ringo", "Rona", "Samuel", "Saw", "Skaarf", "Skye", "Taka", "Vox"]
num = 1
newRandomHero = random.sample(hero_dict,num)
global randHeroName
randHeroName = newRandomHero[0]
print (randHeroName)
heroName = randHeroName

def tab3UI(self):
self.setGeometry(250, 100, 800, 300)
layout = QGridLayout()
hero_dict = ["Adagio", "Alpha", "Ardan", "Baron", "Blackfeather", "Catherine", "Celeste", "Flicker", \
"Fortress", "Glaive", "Gwen", "Idris", "Joule", "Kestrel", "Koshka", "Krul", "Lance", "Lyra", "Ozo", "Petal", \
"Phinn", "Reim", "Ringo", "Rona", "Samuel", "Saw", "Skaarf", "Skye", "Taka", "Vox"]
num = 1
randomHero = random.sample(hero_dict,num)

layout.addWidget(QLabel("Hero:"),0,0)
global heroName
heroName = layout.addWidget(QLabel(randHeroName),0,1)

self.btnRandomHero = QPushButton("Random")
layout.addWidget(self.btnRandomHero,0,3)
self.btnRandomHero.clicked.connect(self.random_her o)

blankSpaceLabel1 = layout.addWidget(QLabel(""),0,4,0,8)
blankSpaceLabel1 = layout.addWidget(QLabel(""),1,0,0,8)

self.setTabText(2,"Ultimate Bravery")
self.tab3.setLayout(layout)

anda_skoa
1st February 2017, 08:52
If you need to access an object from multiple places you need to store it in a variable that is accessible from all those places.

E.g. a member variable in a class or a global variable.

In your case you need to store the QLabel object that you want to use for displaying the hero name.
Then, in your random_hero function, you can write the new name to its "text" property or call its "setText()" function.

Cheers,
_