2017-03-17 29 views
1

我一直在我的程序中遇到這個錯誤,我不知道如何解決它,因爲我是python 3中的初學者。每當我嘗試更改時就會發生錯誤菜單內的網格大小。然後我去運行寶藏網格,我得到這個錯誤,並沒有線索如何解決。任何和所有的幫助表示讚賞!無法處理的類型:int()<Entry()

錯誤:

Exception in Tkinter callback 
Traceback (most recent call last): 
    File "C:\Program Files (x86)\python\lib\tkinter\__init__.py", line 1533, in __call__ 
    return self.func(*args) 
    File "/Documents/treasurehunt test.py", line 178, in refresh 
    placeChests() 
    File "/Documents/treasurehunt test.py", line 128, in placeChests 
    while len(treasureChests) < treasure_amount: 
TypeError: unorderable types: int() < Entry() 

代碼:

from tkinter import * 
import tkinter as tk 
import random 


GridSizeSetByUser = '8x8' 
choicesRows = ['8', '10', '12', '14'] 
v = choicesRows[0] 
choicesColumns = ['8', '10', '12', '14'] 
v2 = choicesColumns[0] 

treasure_amount = 10 
treasureChests = [] 
treasureLocation = [] 
GridRows = 10 
GridColumns = 10 

my_string = my_second_string = grid_row_spinbox = grid_column_spinbox = None 


def get_rows(): 
    global GridRows 
    GridRows = int(grid_row_spinbox.get()) 
    print(repr(GridRows)) 


def get_columns(): 
    global GridColumns 
    GridColumns = int(grid_column_spinbox.get()) 
    print(repr(GridColumns)) 

def create_window(): 
    t_child = tk.Toplevel() 
    t_child.title("Instructions") 
    tInstructions = tk.Label(t_child, fg="magenta",text="""Find the treasure hidden deep in the sand!\n Use ye arrow keys to move around, then press Space to search that spot!\n Keep searching until ye find it!""") 
    tInstructions.pack(side="top", fill="both", expand=False, padx=10, pady=10) 
    quit_button = tk.Button(t_child, text="I'm ready to find some treasure!", width=50, fg="magenta", command=t_child.destroy) 
    quit_button.pack() 
    t_child.attributes('-topmost', True) # note - before topmost 

def treasure_hunt_window(): 
    t_hunt = tk.Tk() 
    t_hunt.title("Treasure Hunt") 
    board = GameBoard(t_hunt) 
    board.pack(side="top", fill="both", expand="true", padx=4, pady=4) 

    create_window() 
    t_hunt.mainloop() 


def settings_window(): 
    global my_string, my_second_string, grid_row_spinbox, grid_column_spinbox 
    settings = tk.Tk() 
    settings.title("Settings") 
    settings_welcome = tk.Label(settings, text='Settings Menu', width=50, 
           fg="magenta") 
    settings_grid_size = tk.Label(settings, text='Grid Size:', width=50, 
            fg="magenta") 
    my_string = StringVar() 
    my_second_string = StringVar() 
    grid_row_spinbox = Spinbox(settings, values=choicesRows, 
           textvariable=my_string, width=50, 
           state="readonly", fg="magenta") 
    save_row_size = tk.Button(settings, text='Save row size for grid', 
           width=50, fg="magenta", command=get_rows) 
    grid_column_spinbox = Spinbox(settings, values=choicesColumns, 
            textvariable=my_second_string, 
            state="readonly", width=50, fg="magenta") 
    save_column_size = tk.Button(settings, text='Save column size for grid', 
           width=50, fg="magenta", command=get_columns) 
    # settings_bandits = tk.Label(settings, text='Amount of Bandits:', 
    #        width=50, fg="magenta") 
    global treasure_amount 
    treasure_amount = tk.Entry(settings, width=50, fg="magenta") 
    settings_Treasure = tk.Label(settings, 
           text='Amount of Treasure Chests (up to 64)', 
           width=50, fg="magenta") 
    settings_welcome.pack(fill=X) 
    settings_grid_size.pack(fill=X) 
    grid_row_spinbox.pack(fill=X) 
    save_row_size.pack(fill=X) 
    grid_column_spinbox.pack(fill=X) 
    save_column_size.pack(fill=X) 
    settings_Treasure.pack(fill=X) 
    treasure_amount.pack(fill=X) 


def main(): 
    root = tk.Tk() 
    root.title("Menu") 
    welcome_button = tk.Label(root, text='Welcome to the menu!', width=50, 
           height=2, fg="magenta") 
    welcome_button.pack(fill=X) 
    start_button = tk.Button(root, text='Start treasure hunting!', width=50, 
          fg="magenta", command=treasure_hunt_window) 
    start_button.pack(fill=X) 
    settings_button = tk.Button(root, text='''\ 
Change the settings of the treasure hunting game. 
This includes the grid size.''', width=50, fg="magenta", 
           command=settings_window) 
    settings_button.pack(fill=X) 
    # display message in a child window. 
    quit_button = tk.Button(root, text='Exit the program', width=50, 
          fg="magenta", command=root.destroy) 
    quit_button.pack(fill=X) 
    root.mainloop() 


def test_stuff(): 
    print(GridRows) 
    print(GridColumns) 


def key_pressed(self, event): 
    if event.keysym == "Right" and self.current_pos[1] < 7: 
     self.current_pos[1] += 1 
    elif event.keysym == "Left" and self.current_pos[1] > 0: 
     self.current_pos[1] -= 1 
    elif event.keysym == "Up" and self.current_pos[0] > 0: 
     self.current_pos[0] -= 1 
    elif event.keysym == "Down" and self.current_pos[0] < 7: 
     self.current_pos[0] += 1 
    elif event.keysym == "Return": 
     self.process_guess() 
    self.matrix = [["#" for col in range(8)] for row in range(8)] 

def placeChests(): 
    while len(treasureChests) < treasure_amount: 
     x = random.randrange(GridColumns) 
     y = random.randrange(GridRows) 
     treasureLocation = [x, y] 
     if treasureLocation not in treasureChests: 
      global treasureChests 
      treasureChests.append(treasureLocation) 
      print (treasureChests) 

class GameBoard(tk.Frame): 
    def __init__(self, parent, size=48, color1="white", color2="black"): 
     """size is the size of a square, in pixels""" 

     self.rows = GridRows 
     self.columns = GridColumns 
     self.size = size 
     self.color1 = color1 
     self.color2 = color2 
     self.pieces = {} 

     canvas_width = GridColumns * size 
     canvas_height = GridRows * size 

     tk.Frame.__init__(self, parent) 
     self.canvas = tk.Canvas(self, borderwidth=0, highlightthickness=0, 
           width=canvas_width, height=canvas_height, 
           background="green") 
     self.canvas.pack(side="top", fill="both", expand=True, padx=2, pady=2) 

     self.canvas.bind("<Configure>", self.refresh) 

    def addpiece(self, name, image, row=0, column=0): 
     '''Add a piece to the playing board''' 
     self.canvas.create_image(0,0, image=image, tags=(name, "piece"), anchor="c") 
     self.placepiece(name, row, column) 

    def placepiece(self, name, row, column): 
     '''Place a piece at the given row/column''' 
     self.pieces[name] = (row, column) 
     x0 = (column * self.size) + int(self.size/2) 
     y0 = (row * self.size) + int(self.size/2) 
     self.canvas.coords(name, x0, y0) 

    def refresh(self, event): 
     """Redraw the board, possibly in response to window resize""" 
     x_size = int((event.width-1)/self.columns) 
     y_size = int((event.height-1)/self.rows) 
     self.size = min(x_size, y_size) 
     self.canvas.delete("square") 
     color = self.color2 
     placeChests() 
     for row in range(self.rows): 
      color = self.color1 if color == self.color2 else self.color2 
      for col in range(self.columns): 
       x1 = (col * self.size) 
       y1 = (row * self.size) 
       x2 = x1 + self.size 
       y2 = y1 + self.size 
       self.canvas.create_rectangle(x1, y1, x2, y2, outline="black", 
              fill=color, tags="square") 
       color = self.color1 if color == self.color2 else self.color2 
     for name in self.pieces: 
      self.place_piece(name, self.pieces[name][0], self.pieces[name][1]) 
     self.canvas.tag_raise("piece") 
     self.canvas.tag_lower("square") 


if __name__ == '__main__': 
    main() 

回答

3

只處理特定問題,你與tk.Entry()即比較int()len(treasureChests) < treasure_amount len返回一個inttreasure_amount是輸入框。要只解決這個問題,while循環改成這樣:

while len(treasureChests) < int(treasure_amount.get()): 

使用.get()它檢索輸入框的值,並int()從默認str 轉換有可能是更多的問題,後來就上來了。

請注意,儘量少用global聲明。

編輯進一步檢查後,我看到這是一個常見的名稱錯誤,你有兩個不同的對象設置爲相同的變量。第一個是在頂部:

treasure_amount = 10 

另外一個是在你的settings_window:

global treasure_amount 
treasure_amount = tk.Entry(settings, width=50, fg="magenta") 

那麼你或許應該改變他們的名字之一。

+0

@ Timothy1224好的,很抱歉,儘管我的回答是,在更改我的代碼之前,* full * traceback是什麼?查看完整的錯誤追溯來診斷您的問題非常重要。 – abccd

+0

啊我明白了爲什麼......看看我的編輯 – abccd

+0

不,因爲在開始時看不到這個常見錯誤 – abccd

相關問題