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

标签 python python-3.x tkinter

我正在做的一个项目让我使用 tkinter 制作游戏板,我从未使用过 tkinter 并且不确定如何实现我想要的。

我使用canvas.createRectangle()制作了一个20x20的方 block 。但我无法更改指定部分的颜色(例如第 8 行第 12 列的部分。)

我需要一种方法来更改特定图 block 填充颜色,并且希望此函数能够接受任何坐标并将颜色更改为指定的任何颜色。

如果有比使用 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. 您正在查看游戏板。

有关代码的重要信息:

  • 这是一项作业,因此我必须删除许多其他代码,但这应该足以显示我需要帮助解决的问题。
  • 此 GUI 仅在 1920x1080 分辨率下正确显示,但可以通过更改宽度和高度值来更改。 (这与问题无关,但如果您想运行它进行自己的测试,这会很有帮助。)
  • 我在按钮上使用的图像已被删除
  • 右侧按钮显示游戏板
  • 左侧按钮关闭游戏
  • 无法扩展并不是问题

预先非常感谢任何可以提供帮助的人!

最佳答案

这是更新后的代码:

#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 行调用了该函数的示例。至于访问图 block 的问题,我在 board 函数中添加了两行,以便它将所有创建的图 block 存储在字典中。该字典的键是一个元组(行,列),从零开始。另外,因为我没有用于按钮的图片,所以我将它们更改为文本,以便我可以运行脚本。请随意将它们改回来。

关于python - 如何在 Tkinter 中创建 20x20 的图 block 网格,然后更改特定图 block 的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43432676/

相关文章:

Python tkinter on matplotlib 如何更新?

python - 访问使用 for 循环创建的 Entry 小部件

python - 使用 Cerberus 验证两个参数具有相同数量的元素

python - 从 numpy.genfromtxt 获取标题行

python - 如何在 Python 中检索 tkinter ttk Scale 小部件的整数值?

python - 使用 Python 将数据转换为图像

python - 如果值匹配,则将一个字典数组中的特定值合并到另一个字典数组中

python - 类函数的文本输出? -Tkinter

linux - 看不到 pylab 的情节

python-3.x - 如何使用 basemap Python 在背景之上绘制散点图