tkinter:如何用图像替换按钮?

时间:2017-11-09 21:44:43

标签: python tkinter

我正在尝试创建一个tic-tac-toe游戏,其中3x3网格或矩阵包含可点击按钮。当按下一个按钮对象时,我希望用一个X或O的图像替换该按钮。这是我到目前为止所拥有的。任何帮助都会很棒。

App.fetchItemById = function (id) {
    App.myItem = new App.Item({id: id});
    App.myItem.fetch({
        traditional: true,
        data: {
            elements: 'all',
            format:'json',
        },
        success: function(){
            App.myItemView = new App.ItemView({
                el: $('#active-item'),
                model: App.myItem,
            });
            App.myItemView.render();
        }
    });
};

2 个答案:

答案 0 :(得分:1)

获取图像的按钮可能有点棘手(你需要一种2层的方法),但更改图像很容易。

x_image = 'x.png'
o_image = 'o.png'

...然后

x_image_for_button = PhotoImage(file=x_image)
o_image_for_button = PhotoImage(file=o_image)

然后.....

button = tk.Button(self.controller, image=o_image_for_button, command=lambda: command_or_something)
button.config(width="40", height="40")
button.place(x=5, y=5)

(添加自我。或root。等)

现在您所做的只是更改图片:

button.set(image=o_image_for_button)
#on second thought... maybe use button.config(image=o_image_for_button) insted

简单:)

答案 1 :(得分:0)

您必须将按钮编号发送到setX功能,以便它知道单击了哪个按钮。此外,您还应检查按钮是否已被点击。

from tkinter import *
from functools import partial

def setX(button_num) :
    ##x = PhotoImage(file = 'E:\X.png')

    ## if button hasn't been clicked before, change the
    ## color and text, and add to list of buttons clicked
    if button_num not in clicked_buttons:
        b[button_num].config(text="X or O")
        b[button_num].config(bg="red")
        clicked_buttons.append(button_num)
    else:
        print("Already clicked")

def create_grid(event=None):
    w = c.winfo_width() # Get current width of canvas
    h = c.winfo_height() # Get current height of canvas
    c.delete('grid_line') # Will only remove the grid_line

    # Creates all vertical lines at intevals of 100
    for i in range(0, w, 200):
        c.create_line([(i, 0), (i, h)], tag='grid_line')

    # Creates all horizontal lines at intevals of 100
    for i in range(0, h, 200):
        c.create_line([(0, i), (w, i)], tag='grid_line')

root = Tk()     
c = Canvas(root, height=600, width=600, bg='white')
c.pack(fill=BOTH, expand=True)

c.bind('<Configure>', create_grid)

b = []
place_positions=[60, 265, 455, 60, 265, 455, 60 ,265, 455]
for _ in range(9):

    ## add a command= to call the setX function and
    ## pass this button number to it using partial
    b.append(Button(c, text="Click", width=10,
             command=partial(setX, _)))
    this_y=475
    if _ < 6:
        this_y=275
    if _ < 3:
        this_y=70
    b[_].place(x=place_positions[_], y=this_y)

"""
b[0].place(x = 60, y = 70)
b[1].place(x = 265, y = 70)
b[2].place(x = 455, y = 70)
b[3].place(x = 60, y = 275)
b[4].place(x = 265, y = 275)
b[5].place(x = 455, y = 275)
b[6].place(x = 60, y = 475)
b[7].place(x = 265, y = 475)
b[8].place(x = 455, y = 475)
"""
clicked_buttons=[]

root.resizable(width=False, height=False)
root.mainloop()