【问题标题】:How to put variable into a label text?如何将变量放入标签文本中?
【发布时间】:2018-07-14 02:50:17
【问题描述】:

我写了一个带有标签的 tkinter 代码。标签文本中有一个变量。

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

当我运行代码时,它在这里给出了一条错误消息: , x,

它说:位置参数跟随关键字参数

【问题讨论】:

  • 那你写text='randomstrings',那么x应该填什么参数呢?

标签: python tkinter label


【解决方案1】:

使用逗号将字符串拼接在一起仅适用于print 函数。您需要自己进行字符串格式化的其他地方:

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

【讨论】:

    【解决方案2】:

    您必须将所有标签块放在一起,然后再将它们传递给Label

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

    或:

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

    【讨论】:

      【解决方案3】:

      你的问题

      逗号用于分隔Label() 的参数,因此x'randomstrings' 被解释为Label() 参数。这不是你想要的。

      解决方案

      你需要连接你的字符串。

      您可以使用+ 运算符来执行此操作:

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

      如果x不是字符串,可以用str()进行转换,像这样:

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

      【讨论】:

        猜你喜欢
        • 2013-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-13
        • 2022-12-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多