TypeError:/:' int'不支持的操作数类型和' str'制作网格时

时间:2017-03-10 09:20:11

标签: python python-3.x tkinter typeerror

我是python和tkinter的新手,每当我尝试为我的程序添加自定义网格大小时,我就会收到以下错误。我非常确定这不是所有其他线程中的重复线程,它们都不涉及网格或在其问题中使用网格功能。

  

TypeError:/:' int'不支持的操作数类型和' str'制作网格时

每当我尝试在GUI中更改GridSize的值时,就会出现错误。您可以在'更改寻宝游戏的设置中更改它的值。菜单的一部分。我是python的新手,所以请用最简单的术语来表达它!

这是我的代码:

import tkinter
import math
import random
from tkinter import *
import tkinter as tk
from tkinter import ttk



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

GridRows = 9
GridColumns = 9


def getRows():
    global GridRows
    GridRows = GridRowSpinbox.get()
    print(GridRows)

def getColumns():
    global GridColumns
    GridColumns = GridColumnSpinbox.get()
    print(GridColumns)

def Treasure_Hunt_Window():
    THunt = tk.Tk()
    THunt.title("Treasure Hunt")
    THuntInstructions = "Find the treasure hidden deep in the sand!Use ye arrow keys to move around,\n\n then press Space to search that spot! Keep searching until ye find it!"
    board = GameBoard(THunt)
    board.pack(side="top", fill="both", expand="true", padx=4, pady=4)
    THunt.mainloop()

def Settings_Window():
    Settings = tk.Tk()
    Settings.title("Settings")
    SettingsWelcome = tk.Label(Settings, text='Settings Menu', width=50, fg="magenta")
    SettingsGridSize = tk.Label(Settings, text='Grid Size:', width =50, fg="magenta")
    global mystring
    mystring = StringVar()
    global mystring2
    mystring2 = StringVar()
    global GridRowSpinbox
    GridRowSpinbox = Spinbox(Settings, values=choicesRows, textvariable=mystring, width=50, state="readonly", fg="magenta")
    SaveRowSize = tk.Button(Settings, text='Save row size for grid', width=50, fg="magenta", command = getRows)
    global GridColumnSpinbox
    GridColumnSpinbox = Spinbox(Settings, values=choicesColumns, textvariable=mystring2, state="readonly", width=50, fg="magenta")
    SaveColumnSize = tk.Button(Settings, text='Save column size for grid', width=50, fg="magenta", command = getColumns)
    SettingsBandits = tk.Label(Settings, text='Amount of Bandits:', width =50, fg="magenta")
    BanditAmount = tk.Entry(Settings, width = 50, fg="magenta")
    SettingsBandits = tk.Label(Settings, text='Amount of Treasure Chests (up to 64)', width =50, fg="magenta")
    SettingsWelcome.pack(fill=X)
    SettingsGridSize.pack(fill=X)
    GridRowSpinbox.pack(fill=X)
    SaveRowSize.pack(fill=X)
    GridColumnSpinbox.pack(fill=X)
    SaveColumnSize.pack(fill=X)
    SettingsBandits.pack(fill=X)
    BanditAmount.pack(fill=X)



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

def teststuff():
    print(GridRows)
    print(GridColumns)

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 refresh(self, event):
        '''Redraw the board, possibly in response to window being resized'''
        xsize = int((event.width-1) / self.columns)
        ysize = int((event.height-1) / self.rows)
        self.size = min(xsize, ysize)
        self.canvas.delete("square")
        color = self.color2
        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.placepiece(name, self.pieces[name][0], self.pieces[name][1])
        self.canvas.tag_raise("piece") 
        self.canvas.tag_lower("square")

main()

1 个答案:

答案 0 :(得分:0)

请继续处理您的程序,但请使用以下代码替换您的代码并从那里开始工作。您可能还希望通过PEP8 online网站运行代码。对您的代码所做的更改包括确保没有生成错误或警告。

要回答您的问题,下面的两个功能与您的代码最初的功能略有不同。请注意前两个函数get_rowsget_columns。从Spinbox获取信息时,您需要在使用之前将数据转换为正确的类型。

from tkinter import *
import tkinter as tk


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

GridRows = 9
GridColumns = 9

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 treasure_hunt_window():
    t_hunt = tk.Tk()
    t_hunt.title("Treasure Hunt")
#     t_hunt_instructions = """\
# Find the treasure hidden deep in the sand!Use ye arrow keys to move around,
#
# then press Space to search that spot! Keep searching until ye find it!"""
    board = GameBoard(t_hunt)
    board.pack(side="top", fill="both", expand="true", padx=4, pady=4)
    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")
    bandit_amount = tk.Entry(settings, width=50, fg="magenta")
    settings_bandits = 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_bandits.pack(fill=X)
    bandit_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)


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

    def place_piece(self, name, a, b):
        pass


if __name__ == '__main__':
    main()