0

I'm creating BattleShip in Python 3.4.1 and I'm using Tkinter.

This is my 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():
    for i in range(0,10):
        global self
        for 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 I want to do a function based on what button is pressed. How do I do that?

1 Answer 1

2

Make the press function to accept an additional parameter.

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

And pass the button text to the 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: use of keyword argument in lambda to bind the current value of i, j. If you don't use keyword argument, i, j, .. will reference the last values that was assigned in the loop.

BTW, grid returns nothing (= return None). Assigning the return value to a variable does not have meaning.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for your quick response. However, it didn't seem to work. I don't understand the comma in the print statement. Was that a typo or something? Relatively new to python, but when I used your code it had errors galore.
Also, I am aware that i and j reference the last values. Any way to stop that?
@3.14-Thon, , text is there to print text passed.
When I ran that, it didn't work... Specifically, it reported that "text is not defined"
@3.14-Thon, I think you didn't change the signature of the function press. Try this (full code): pastebin.com/nnHLvdLM
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.