簡體   English   中英

按鈕網格:單擊時更改一個的顏色

[英]Grid of buttons: Change color of one when it is clicked

所以我有一個像這樣創建的按鈕網格(在Python 3.4上使用Tkinter):

from tkinter import *

vText = [ "A","B","C","D","E","F","G","H","I","J" ]
boat  = [ "A1","A2","A3" ]
shots = []

def press( pos, b, pos2 ):
    if pos in shots:
        print( "You've chosen this already!" )
    else:
        shots.append( pos )
        if pos in boat:
            print( "Hit!" )
            b[pos2].configure( bg = "red", fg = "white" )
        else:
            print( "Miss." )
            b[pos2].configure( bg = "blue", fg = "white" )

root   = Tk()
button = []
row    = []
column = []
for a in range( 1, 102 ):
    button.append( a )
    row.append(    a )
    column.append( a )

for i in range( 0, 10 ):
    for j in range( 1, 11 ):
        p2 = i * 10 + j
        button[p2] = Button( root, text    = vText[i] + str(j),                   \
                                   command = lambda i=i, j=j, position=vText[i] + str(j): press( position, button, p2 ), \
                                   padx    = 25,                                  \
                                   pady    = 25,                                  \
                                   bg      = "#66CCCC"                            \
                                   )
        button[p2].grid( row = i, column = j )

root.wm_title( "Enemy grid" )
root.mainloop()

如您所見,我已經嘗試過(在press()定義中)完成此工作,但是pos2僅能夠引用最后一個,因為pos2for循環中使用了ij

這是BattleShip代碼的一部分,因此,自此以來,我添加了一些點滴。 但是,問題是相同的。 我希望能夠單擊一個,並使其在單擊時更改顏色。 必須能夠創建所有100個按鈕。 此外,如果擊中,我需要將其變為紅色;如果未擊中,則需要將其變為藍色。

提前致謝。

為了在Tkinter(或任何GUI框架,盡管這些術語和技巧非常有用)中使用按鈕,您需要將功能綁定到按鈕。

例如:

from functools import partial

def my_func_name(sequence, index):
    widget = sequence[index]
    widget.configure(bg='white') #  for example

for i in range(0,10):
    for j in range(1,11):
        p2 = i * 10 + j
        par = partial(my_func_name, button, p2)
        button[p2] = Button(root, text = vText[i] + str(j), command=par, padx=25, pady=25, bg = "#66CCCC")
        button[p2].grid(row=i, column=j)

Effbot在Tkinter上寫了一本相當不錯的書(免費),還有Tkdocs ,這是一個很棒的教程,它涵蓋了比SO問題更詳細的基礎知識。

該答案已經過編輯,以反映出我第一次回答該問題時的愚蠢行為。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM