How to put variable into a label text?

…衆ロ難τιáo~ 提交于 2021-02-04 21:56:29

问题


I wrote a tkinter code, with a label. There was a variable in the label text.

lab = Label(root, text = 'randomstrings', x, 'randomstrings')
    lab.pack()

When I ran the code, it gave an error message here: , x,

It said: positional argument follows keyword argument


回答1:


You must put all label pieces together before passing them to the Label:

Label(root, text = 'randomstrings' + str(x) + 'randomstrings', ...)

or:

Label(root, text = 'randomstrings{}randomstring'.format(x), ...)



回答2:


Using commas to stitch strings together only works in the print function. Everywhere else you need to do the string formatting yourself:

lab = Label(root, text = 'randomstrings {} randomstrings'.format(x))
lab.pack()



回答3:


Your problem

Commas are used to separate Label()'s arguments, so x and 'randomstrings' are interpreted as Label() arguments. This is not what you want.

Solution

You need to concatenate your strings.

You can use the + operator to do so:

lab = Label(root, text = 'randomstrings ' + x + ' randomstrings')
lab.pack()

If x is not a string, you can convert it with str(), like this:

lab = Label(root, text = 'randomstrings ' + str(x) + ' randomstrings')
lab.pack()


来源:https://stackoverflow.com/questions/48602394/how-to-put-variable-into-a-label-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!