unorderable类型:int()<条目()

时间:2017-03-17 09:13:04

标签: python python-3.x tkinter

我在程序中一直遇到这个错误,我不知道如何修复它,因为我是python 3中的初学者。每当我尝试在菜单中更改网格的大小时就会出现错误。然后我去运行宝藏网格,我得到这个错误,并不知道如何解决。任何和所有的帮助表示赞赏!

错误:

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()

1 个答案:

答案 0 :(得分:3)

只处理该特定问题,您将int()tk.Entry()进行比较,即。 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")

所以你应该改变其中一个的名字。