这是一个小例子和演示——它拥有启动程序所需的一切。查看代码中的注释:
import tkinter
app = tkinter.Tk()
# Create a set for all clicked buttons (set prevents duplication)
clicked = set()
# Create a tuple of words (your 180 verb goes here)
words = 'hello', 'world', 'foo', 'bar', 'baz', 'egg', 'spam', 'ham'
# Button creator function
def create_buttons( words ):
# Create a button for each word
for word in words:
# Add text and functionality to button and we are using a lambda
# anonymous function here, but you can create a normal 'def' function
# and pass it as 'command' argument
button = tkinter.Button( app,
text=word,
command=lambda w=word: clicked.add(w) )
# If you have 180 buttons, you should consider using the grid()
# layout instead of pack() but for simplicity I used this one for demo
button.pack()
# For demo purpose I binded the space bar, when ever
# you hit it, the app will print you out the 'clicked' set
app.bind('<space>', lambda e: print( *clicked ))
# This call creates the buttons
create_buttons( words )
# Now we enter to event loop -> the program is running
app.mainloop()
编辑:
这是没有lambda 表达式的代码:
import tkinter
app = tkinter.Tk()
# Create a set for all clicked buttons (set prevents duplication)
clicked = set()
# Create a tuple of words (your 180 verb goes here)
words = 'hello', 'world', 'foo', 'bar', 'baz', 'egg', 'spam', 'ham'
# This function will run when pressing the space bar
def on_spacebar_press( event ):
print( 'Clicked words:', *clicked )
# Button creator function
def create_buttons( words ):
# Create a button for each word
for word in words:
# This function will run when a button is clicked
def on_button_click(word=word):
clicked.add( word )
# Add button
button = tkinter.Button( app,
text=word,
command=on_button_click )
# If you have 180 buttons, you should consider using the grid()
# layout instead of pack() but for simplicity I used this one for demo
button.pack()
# Binding function tp space bar event
app.bind('<space>', on_spacebar_press)
# This call creates the buttons
create_buttons( words )
# Now we enter to event loop -> the program is running
app.mainloop()