Python的相对noob,仍在学习所有的细节,但我正在学习。我正在为我正在进行的个人项目第一次潜入GUI。 (我是一名语言学研究生,这将大大提高我的研究能力。)我知道Tkinter和Button课程(基本上,他们存在),但我需要一些帮助才能让我开始。我想一旦我知道了神奇的话语,我就能适应我需要的情况。
基本上,我有大约180个单词的示例文本摘录。我想要做的是找出一种创建GUI界面的方法,使180字的摘录中的每个单词都显示为一个单独的按钮,并提示用户,例如,单击动词。点击的值将被存储,然后我继续查看下一个问题。
我需要知道的事情: 如何根据文本的内容创建按钮。 (我假设每个按钮都需要一个不同的变量名。) - 如果一个摘录的长度与另一个摘录的长度不同,这是否重要? (我假设没有。) - 如果摘录中有几个相同的单词,这是否重要? (我假设没有,因为您可以使用索引来记住单击单词在原始摘录中的位置。) 如何根据单击的按钮存储数据。 如何清理石板,继续我的下一个问题。
提前感谢您的帮助。
答案 0 :(得分:2)
这是一个小例子和演示 - 它拥有启动程序所需的一切。请参阅代码中的注释:
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()