简体   繁体   English

更改按钮的内容时,如何使此代码更加自动化?

[英]How can i make this code more automated when changing the content of the buttons?

I made this code to start making a TicTacToe game, i'm pretty sure there's a way of making one function that changes the content of the button that has been last pressed or something similar. 我编写了这段代码,开始制作TicTacToe游戏,我敢肯定,有一种方法可以使一个函数改变上次按下的按钮或类似内容。

How can i make it into a more shorter version? 如何将其制作成更短的版本?

I think i can use .self and make one fucntion but i don't know how. 我认为我可以使用.self并实现一项功能,但我不知道如何做。

import tkinter as tk

main = tk.Tk()

l1b1 = tk.StringVar()
l1b1.set("0")
l1b2 = tk.StringVar()
l1b2.set("0")
l1b3 = tk.StringVar()
l1b3.set("0")

l2b1 = tk.StringVar()
l2b1.set("0")
l2b2 = tk.StringVar()
l2b2.set("0")
l2b3 = tk.StringVar()
l2b3.set("0")

l3b1 = tk.StringVar()
l3b1.set("0")
l3b2 = tk.StringVar()
l3b2.set("0")
l3b3 = tk.StringVar()
l3b3.set("0")


def l1b1co():
l1b1.set("x")


def l1b2co():
    l1b2.set("x")


def l1b3co():
    l1b3.set("x")


def l2b1co():
    l2b1.set("x")


def l2b2co():
l2b2.set("x")


def l2b3co():
    l2b3.set("x")


def l3b1co():
    l3b1.set("x")


def l3b2co():
    l3b2.set("x")


def l3b3co():
    l3b3.set("x")


tk.Button(main, textvariable=l1b1, command=l1b1co).grid(column=0, row=0)
tk.Button(main, textvariable=l1b2, command=l1b2co).grid(column=1, row=0)
tk.Button(main, textvariable=l1b3, command=l1b3co).grid(column=2, row=0)

tk.Button(main, textvariable=l2b1, command=l2b1co).grid(column=0, row=1)
tk.Button(main, textvariable=l2b2, command=l2b2co).grid(column=1, row=1)
tk.Button(main, textvariable=l2b3, command=l2b3co).grid(column=2, row=1)

tk.Button(main, textvariable=l3b1, command=l3b1co).grid(column=0, row=2)
tk.Button(main, textvariable=l3b2, command=l3b2co).grid(column=1, row=2)
tk.Button(main, textvariable=l3b3, command=l3b3co).grid(column=2, row=2)

main.mainloop()

The simplest solution is to use a dictionary or list of lists, and create everything in a loop. 最简单的解决方案是使用字典或列表列表,然后循环创建所有内容。

Since you're creating three rows with three columns, you can use a loop to iterate over the rows, and in each iteration you can loop over the columns. 由于您要创建具有三列的三行,因此可以使用循环来遍历行,并且在每次迭代中都可以遍历列。 You can use the row and column number to reference each variable or button. 您可以使用行号和列号来引用每个变量或按钮。

Example: 例:

import tkinter as tk

main = tk.Tk()

buttons = {}
button_vars = {}

def setVar(row, column, value):
    button_vars[row, column].set(value)

for row in range(3):
    for column in range(3):
        var = tk.StringVar(value="0")
        button = tk.Button(main, textvariable=var,
                           command=lambda row=row, column=column: setVar(row, column, "x"))
        button.grid(row=row, column=column)

        button_vars[row, column] = var
        buttons[row, column] = button

main.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM