如何在Tkinter中创建20x20网格,然后更改特定图块的颜色

时间:2017-04-16 00:56:17

标签: python python-3.x tkinter

我正在做的一个项目让我使用tkinter制作游戏板,我还没有使用过tkinter而且我不确定如何完成我想要的东西。

我使用canvas.createRectangle()创建了一个20x20的正方形板。但我无法改变指定作品的颜色(比如说第8行和第12列的作品。)

我需要一种方法来更改特定的瓷砖填充颜色,并希望此功能能够接收任何坐标并将颜色更改为指定的任何颜色。

如果有比使用createRectangle更好的方法,请告诉我!

我尝试做的是在每个制作的矩形上设置标签,但我无法弄清楚如何使用标签来引用每个矩形。

这是我到目前为止所做的:

#imports
from tkinter import *

#-------------- SET UP THE WINDOW FRAME --------------------------------
class launchScreen(Frame):
    #set the initial size of the window please change width and height
    #it uses these values to determine the window size
    #if you are on a resolution that is not 1920x1080

    def __init__(self, master=None, width=0.5, height=0.4):
        Frame.__init__(self, master)
        #pack the frame to cover the whole window
        self.pack(side=TOP, fill=BOTH, expand=YES)

        # get screen width and height
        ws = self.master.winfo_screenwidth()
        hs = self.master.winfo_screenheight()

        w = ws*width
        h = ws*height
        # calculate position x, y
        x = (ws/2) - (w/2)
        y = (hs/2) - (h/2)
        self.master.geometry('%dx%d+%d+%d' % (w, h, x, y))

        #Make the screen appear on top of everything.
        self.master.overrideredirect(True)
        self.lift()
#Once it has launched do everything in Main
if __name__ == '__main__':
    root = Tk()
    #set the title of the applicaton window
    root.title('Blokus')

#--------------------- GAME STARTED ----------------------------------------
    def gameStart():

        print("Game Started")
        #get rid of the launch screen elemenets and show the game board
        LaunchScrn.pack_forget()

        #this is where the 20x20 grid is made
        #set up the view of the game board
        def board(view):
            w=view.winfo_width()
            h=view.winfo_height()
            gridWidth = w / 20
            gridHeight = h / 20
            rowNumber = 0
            for row in range(20):
                columnNumber = 0
                rowNumber = rowNumber + 1
                for col in range(20):
                        columnNumber = columnNumber + 1
                        rect = view.create_rectangle(col * gridWidth,
                         row * gridHeight,
                         (col + 1) * gridWidth,
                         (row + 1) * gridHeight,
                         fill = '#ccc')
                         #Sets row, column
                        view.itemconfig(rect, tags=(str(rowNumber), str(columnNumber)))


        #set up the canvas for the game board grid
        viewCanvas = Canvas(root, width=root.winfo_width(), height=root.winfo_height(),bg="#ddd")
        viewCanvas.pack(side=TOP, fill=BOTH,padx=1,pady=1)

        #when you click on the gameboard this event fires
        def clickOnGameBoard(event):
            if viewCanvas.find_withtag(CURRENT):
                print(viewCanvas.gettags(CURRENT))
                print(type(viewCanvas.gettags(CURRENT)))
                viewCanvas.itemconfig(CURRENT, fill="yellow")
                viewCanvas.update_idletasks()
        #bind an event when you click on the game board
        viewCanvas.bind("<Button-1>", clickOnGameBoard)

        #update the game board after it is done being drawn.
        root.update_idletasks()

        #show the gameboard in the Canvas
        board(viewCanvas)

        #when you click the quit button it returns you to the launch screen
        def clickToQuit(event):
            viewCanvas.destroy()
            label.pack_forget()
            LaunchScrn.pack(side=TOP, fill=BOTH, expand=YES)

        #sets up the button for the quit
        quitPath = "images/exit.gif"
        quitImg = PhotoImage(file=quitPath)
        label = Label(root, image=quitImg)
        label.image = quitImg # you need to cache this image or it's garbage collected
        #binds clicking this label to the quit event
        label.bind("<Button-1>",clickToQuit)
        label.pack(side=LEFT)

#------------ GAME ENDED --------------------
    def gameEnd():
        #quits the game
        def quitGame():
            print("Game Ended")
            LaunchScrn.after(3000,root.destroy())
        quitGame()

#---------------------------- LAUNCH SCREEN --------------------------------------------
    LaunchScrn = launchScreen(root)
    LaunchScrn.config(bg="#eee")

    b=Button(LaunchScrn, command=gameStart)
    photo2=PhotoImage(file="images/start.gif")
    b.config(image=photo2, width="300", height="50")
    b.pack(side=RIGHT, fill=X, padx=10, pady=10)

    b=Button(LaunchScrn, command=gameEnd)
    photo4=PhotoImage(file="images/quit.gif")
    b.config(image=photo4, width="300", height="50")
    b.pack(side=RIGHT, fill=X, padx=10, pady=10)

    root.mainloop()

显示游戏板:

  1. 启动python文件
  2. 点击右键(两个按钮均为空白)
  3. 你正在看游戏板。
  4. 有关代码的重要信息:

    • 这是一个作业,所以我不得不删除很多其他代码,但这应该足以显示我需要帮助解决的问题。
    • 此GUI仅在1920x1080分辨率下正确显示,但可以通过更改宽度和高度值来更改。 (这不属于这个问题,但是如果你想为自己的测试运行它会很有帮助。)
    • 我在按钮上使用的图片已被删除
    • 右侧显示游戏板的按钮
    • 左侧的按钮关闭游戏
    • 无法缩放的事实不是问题

    非常感谢所有能提供帮助的人!

1 个答案:

答案 0 :(得分:1)

以下是更新后的代码:

#imports
from tkinter import *

#-------------- SET UP THE WINDOW FRAME --------------------------------
class launchScreen(Frame):
    #set the initial size of the window please change width and height
    #it uses these values to determine the window size
    #if you are on a resolution that is not 1920x1080

    def __init__(self, master=None, width=0.5, height=0.4):
        Frame.__init__(self, master)
        #pack the frame to cover the whole window
        self.pack(side=TOP, fill=BOTH, expand=YES)

        # get screen width and height
        ws = self.master.winfo_screenwidth()
        hs = self.master.winfo_screenheight()

        w = ws*width
        h = ws*height
        # calculate position x, y
        x = (ws/2) - (w/2)
        y = (hs/2) - (h/2)
        self.master.geometry('%dx%d+%d+%d' % (w, h, x, y))

        #Make the screen appear on top of everything.
        self.master.overrideredirect(True)
        self.lift()
#Once it has launched do everything in Main
if __name__ == '__main__':
    root = Tk()
    #set the title of the applicaton window
    root.title('Blokus')
    coordinate={}
    def changecolor(row, column, canvas):
        canvas.itemconfig(coordinate[(row, column)], fill='yellow')

#--------------------- GAME STARTED ----------------------------------------
    def gameStart():
        global coordinate
        print("Game Started")
        #get rid of the launch screen elemenets and show the game board
        LaunchScrn.pack_forget()

        #this is where the 20x20 grid is made
        #set up the view of the game board
        def board(view):
            coordinate={}
            w=view.winfo_width()
            h=view.winfo_height()
            gridWidth = w / 20
            gridHeight = h / 20
            rowNumber = 0
            for row in range(20):
                columnNumber = 0
                rowNumber = rowNumber + 1
                for col in range(20):
                        columnNumber = columnNumber + 1
                        rect = view.create_rectangle(col * gridWidth,
                         row * gridHeight,
                         (col + 1) * gridWidth,
                         (row + 1) * gridHeight,
                         fill = '#ccc')
                         #Sets row, column
                        view.itemconfig(rect, tags=(str(rowNumber), str(columnNumber)))
                        coordinate[(row,col)]=rect
            return coordinate

        #set up the canvas for the game board grid
        viewCanvas = Canvas(root, width=root.winfo_width(), height=root.winfo_height(),bg="#ddd")
        viewCanvas.pack(side=TOP, fill=BOTH,padx=1,pady=1)

        #when you click on the gameboard this event fires
        def clickOnGameBoard(event):
            if viewCanvas.find_withtag(CURRENT):
                print(viewCanvas.gettags(CURRENT))
                print(type(viewCanvas.gettags(CURRENT)))
                viewCanvas.itemconfig(CURRENT, fill="yellow")
                viewCanvas.update_idletasks()
        #bind an event when you click on the game board
        viewCanvas.bind("<Button-1>", clickOnGameBoard)

        #update the game board after it is done being drawn.
        root.update_idletasks()

        #show the gameboard in the Canvas
        coordinate=board(viewCanvas)
        changecolor(1, 2, viewCanvas)

        #when you click the quit button it returns you to the launch screen
        def clickToQuit(event):
            viewCanvas.destroy()
            label.pack_forget()
            LaunchScrn.pack(side=TOP, fill=BOTH, expand=YES)

        #sets up the button for the quit
        quitPath = "images/exit.gif"
        quitImg = PhotoImage(file=quitPath)
        label = Label(root, image=quitImg)
        label.image = quitImg # you need to cache this image or it's garbage collected
        #binds clicking this label to the quit event
        label.bind("<Button-1>",clickToQuit)
        label.pack(side=LEFT)




#------------ GAME ENDED --------------------
    def gameEnd():
        #quits the game
        def quitGame():
            print("Game Ended")
            LaunchScrn.after(3000,root.destroy())
        quitGame()

#---------------------------- LAUNCH SCREEN --------------------------------------------
    LaunchScrn = launchScreen(root)
    LaunchScrn.config(bg="#eee")

    b=Button(LaunchScrn,text='start', command=gameStart)
    #photo2=PhotoImage(file="images/start.gif")
    #b.config(image=photo2, width="300", height="50")
    b.pack(side=RIGHT, fill=X, padx=10, pady=10)

    b=Button(LaunchScrn, text='end',command=gameEnd)
    #photo4=PhotoImage(file="images/quit.gif")
    #b.config(image=photo4, width="300", height="50")
    b.pack(side=RIGHT, fill=X, padx=10, pady=10)

    root.mainloop()

基本上,我定义了一个名为changecolor的函数。我还在第88行调用了该函数的示例。至于访问tile的问题,我在board函数中添加了两行,以便将所有创建的tile存储在字典中。该字典的键是元组(row, column),从零开始。另外,因为我没有用于按钮的图片,所以我将它们更改为文本,以便我可以运行脚本。随意改变它们。