问题
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