How to use print in the graphical interface?

Asked

Viewed 276 times

0

I need the result of the function print((randint(0,700)) appear on the label (label) of my program window (created with Py’s own Qt Designer), and not in the interpreter, but only know the command interface.label.setText("") which only shows the text placed, nothing more. That is the programming:

    from random import randint
from PyQt5 import QtWidgets, uic
janela=QtWidgets.QApplication([])
interface=uic.loadUi ("hello_interface.ui")
def PRINT():
    **interface.label.setText("print(randint(0,700))")**
interface.pushButton.clicked.connect(PRINT)
interface.show()
janela.exec

I just need the result of print(randint) instead of the code text, please!

  • It wouldn’t be enough to do interface.label.setText(randint(0,700))?

  • 1

    just need to convert to string - .setText(str(randint(0, 700)) or .setText(f"{randint(0, 700)}")

1 answer

2


The Python 3 print is just a function - although widely used, which converts the parameters passed in sequence to strings, and writes these strings to the file sys.stdout by default.

When we use a graphical interface, it is no use to place the desired contents in sys.stdout, and in general or in another file - but rather, to call methods specific to the components of the graphical interface by passing the text we want to display as a string. No sense trying to use the print, that even returns a value.

In your program, if the method that displays the string in the desired location is the interface.label.setText(...), all you need to do is pass what you want to display as text (string) to it. One of the ways to do this conversion in Python is to use the call str(...) - that will use the internal mechanisms of each object to get its representation in text.

So, probably, all you need there is:


def PRINT():
    interface.label.setText(str(randint(0,700)))

(Probably because without the other files of the project, and etc...I can’t say that this is the correct method to display the text in the desired location)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.