2013-09-28 82 views
1

我正在編寫一個骰子模擬器,它將擲出6面骰子或8面骰子。我正在使用Python 2.7和Tkinter。下面是我用的骰子字典文件:Tkinter Label,TypeError:不能連接'str'和'實例'對象

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"]) 

我的問題是發生在錯誤信息我跑我的文件:

類型錯誤:不能連接「STR」和「實例」對象

任何幫助是極大的讚賞! :)

回答

1

希望你期待這樣的事情:

Example window

你必須通過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 錯誤的發生是因爲數據不能從一個類的字符串或INT的檢索,而無需使用__repr____str__方法而是作爲對象

,因爲你有沒有顯示您的完整代碼,這是我可以幫助的

#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() 
相關問題