【问题标题】:Tkinter Label, TypeError: cannot concatenate 'str' and 'instance' objectsTkinter 标签,TypeError:无法连接“str”和“instance”对象
【发布时间】:2013-09-28 10:03:36
【问题描述】:

我正在编写一个骰子模拟器,可以掷出 6 面骰子或 8 面骰子。我正在使用 Python 2.7 和 Tkinter。这是我的文件,里面有一本带有骰子的字典:

DICE = dict(
    sixsided={'name': 'Six Sided Dice',
              'side': 6},
    eightsided = {'name': 'Eight Sided Dice',
                  'side': 8}
    )
names = ['Six Sided Dice', 'Eight Sided Dice']

这是导致我的问题的主文件中的代码:

diceroll = random.randrange(1,DICE[selecteddice]["side"])
Label(diceroll, text="You rolled a " + diceroll + " on the " + DICE[selecteddice]["name"])

我的问题是运行文件时出现的错误消息:

TypeError: 无法连接 'str' 和 'instance' 对象

非常感谢任何帮助! :)

【问题讨论】:

    标签: python tkinter concatenation typeerror


    【解决方案1】:

    希望你期待这样的事情:

    你必须传递 Tk()假设它被导入为 from Tkinter import * 作为 Tk 小部件的第一个参数:

    root = Tk()
    Label(root, text="You rolled a " + diceroll + " on the " + DICE[selecteddice]["name"])
    

    但现在你会得到TypeError: cannot concatenate 'str' and 'int' objects,所以使用str() 方法将diceroll 转换为字符串

    Label(root, text="You rolled a " + str(diceroll) + " on the " + DICE[selecteddice]["name"])
    

    TypeError: cannot concatenate 'str' and 'instance' objects 发生错误是因为如果不使用 __repr____str__ 方法,则无法从类中以字符串或 int 的形式检索数据 而是作为对象

    由于您尚未显示完整代码,因此我只能提供帮助

    #The top image was produced thanks to this
    import random
    from Tkinter import *
    
    selecteddice = 'sixsided'
    
    DICE = dict(
        sixsided={'name': 'Six Sided Dice',
                  'side': 6},
        eightsided = {'name': 'Eight Sided Dice',
                      'side': 8}
        )
    names = ['Six Sided Dice', 'Eight Sided Dice']
    
    root = Tk()
    
    diceroll = random.randrange(1,DICE[selecteddice]["side"])
    Label(root, text="You rolled a " + str(diceroll) + " on the " + DICE[selecteddice]["name"]).pack()
    
    root.mainloop()
    

    【讨论】:

      猜你喜欢
      • 2011-10-23
      • 2015-09-01
      • 2020-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多