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

2024-09-30 00:41:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做的一个项目让我用tkinter制作游戏板,我从来没有用过tkinter,也不确定如何完成我想要的。在

我用画布.createRectangle(). 但我无法更改指定工件的颜色(例如第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. 你在看游戏板。在

有关代码的重要信息:

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

提前感谢所有能帮忙的人!在


Tags: theselfmasterboardyoudefrootwidth
1条回答
网友
1楼 · 发布于 2024-09-30 00:41:40

以下是更新后的代码:

#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),以零开头。另外,因为我没有你用来做按钮的图片,所以我把它们改成了文本,这样我就可以运行脚本了。你可以把它们换回来。在

相关问题 更多 >

    热门问题