1

我正在编写一个骰子模拟器,可以滚动 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”对象

任何帮助是极大的赞赏!!:)

4

1 回答 1

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()
于 2013-09-28T10:20:55.903 回答