Saturday, 15 June 2013

python - Button Input using Tkinter -



python - Button Input using Tkinter -

i'm creating battleship in python 3.4.1 , i'm using tkinter.

this source code:

from tkinter import * vtext = ["a","b","c","d","e","f","g","h","i","j"] def press(a,b): print("you pressed: " + str(a * 10 + b)) root = tk() def button(): in range(0,10): global self j in range(1,11): self = button(root, text = vtext[i] + str(j), command = lambda: press(i,j), padx = 20, pady = 20).grid(row = i, column = j) root.wm_title("enemy grid") button() root.mainloop()

later want function based on button pressed. how do that?

make press function take additional parameter.

def press(a, b, text): print("you pressed: " + str(a * 10 + b), text)

and pass button text function:

button(root, text = vtext[i] + str(j), command=lambda i=i, j=j, text=vtext[i] + str(j): press(i, j, text), padx=20, pady=20).grid(row=i, column=j)

note: utilize of keyword argument in lambda bind current value of i, j. if don't utilize keyword argument, i, j, .. reference lastly values assigned in loop.

btw, grid returns nil (= homecoming none). assigning homecoming value variable not have meaning.

python python-3.x tkinter python-3.4

No comments:

Post a Comment