2016-04-14 26 views
-1

Tic Tac Toe oyunu yapmaya çalışıyorum, ancak programı her çalıştırdığımda, işlev herhangi bir nedenle otomatik olarak yürütülür. Bugüne kadar aşağıda kodu: i programı çalıştırdığınızdaTkinter .bind() yöntemi

from tkinter import * 

root = Tk() 
root.geometry('200x200') 

x_turn = True 

def button_clicked(b): 
    global x_turn 
    print('Executed') 
     if x_turn is True: 
      b.config(text='X') 
      x_turn = False 
     else: 
      b.config(text='O') 
      x_turn = True 

button1 = Button(root, text='', width=6, height=2) 
button1.bind('<Button1>', button_clicked(button1)) 
button1.grid(row=0, column=0) 

button2 = Button(root, text='', width=6, height=2) 
button2.bind('<Button1>', button_clicked(button2)) 
button2.grid(row=0, column=1) 

button3 = Button(root, text='', width=6, height=2) 
button3.bind('<Button1>', button_clicked(button3)) 
button3.grid(row=0, column=2) 

button4 = Button(root, text='', width=6, height=2) 
button4.bind('<Button1>', button_clicked(button4)) 
button4.grid(row=1, column=0) 

button5 = Button(root, text='', width=6, height=2) 
button5.bind('<Button1>', button_clicked(button5)) 
button5.grid(row=1, column=1) 

button6 = Button(root, text='', width=6, height=2) 
button6.bind('<Button1>', button_clicked(button6)) 
button6.grid(row=1, column=2) 

button7 = Button(root, text='', width=6, height=2) 
button7.bind('<Button1>', button_clicked(button7)) 
button7.grid(row=2, column=0) 

button8 = Button(root, text='', width=6, height=2) 
button8.bind('<Button1>', button_clicked(button8)) 
button8.grid(row=2, column=1) 

button9 = Button(root, text='', width=6, height=2) 
button9.bind('<Button1>', button_clicked(button9)) 
button9.grid(row=2, column=2) 

root.mainloop() 

otomatik fonksiyonu 9 kez çağırır ve nedenini anlamaya olamaz. Bilmediğim bazı garip kurallar var mı?

cevap

1

Otomatik olarak 9 buttonX.bind... numaranızla 9 kez aramanız gerektiği için otomatik olarak button_clicked numaralı telefonu arar.

bind method, bir parametre olarak işlev görür. Bir işlevin içinden geçmiyorsunuz, button_clicked(b)'dan dönüş değerinden geçiyorsunuz.

[button_clicked bir fonksiyonudur, fakat button_clicked(some_parameter) bu işlevi çağırmak ve parametre olarak geri dönüş değeri kullanarak anlamına gelmektedir]

bağlama yöntemi için parametre alan bir fonksiyon olarak geçirmek için bir kaç yöntem vardır. Bir yol, arandığında real işlevinizi çağıran anonim bir lambda expression geçmektir. Bu yerine Yani

:

button1.bind('<Button1>', button_clicked(button1)) 

değişikliğin tüm çağrılar böyle bir şey bakmak i lambda kullandığınızda

button1.bind('<Button1>', lambda: button_clicked(button1)) 
+0

bir hata alıyorum. – jjguidry

+0

@jjguidry: belki şunu deneyin: 'button1.bind ('', command = lambda: button_clicked (button1))'. – Gerrat

+0

Nope :( "bind() beklenmedik bir anahtar kelime argümanına sahip" komut "var" – jjguidry