创建依赖于输入的按钮,获取用户d

2024-06-12 20:40:23 发布

您现在位置:Python中文网/ 问答频道 /正文

从noob到Python,仍然在学习所有的细节,但我正在学习。我第一次潜入GUI是为了我正在做的一个个人项目。(我是语言学研究生,这将大大提高我的研究能力。)我知道Tkinter和Button类(基本上,它们存在),但我需要一些帮助来开始。我想一旦我知道了这些神奇的词,我就能适应我需要的情况。在

基本上,我有大约180个单词的样本文本摘录。我要做的是找出一种方法来创建一个GUI界面,这样180个单词的摘要中的每个单词都会显示为一个单独的按钮,并提示用户,例如,单击动词。被点击的值会被存储起来,然后我会继续问下一个问题。在

我需要知道的是: 如何根据文本创建按钮。(我假设每个按钮都需要一个不同的变量名。) -如果一个节选的长度不同于另一个节选是否重要?(我想不会吧。) -如果节选中有几个相同的词,这有关系吗?(我假设没有,因为您可以使用索引来记住单击的单词在原始摘录中的位置。) 如何根据单击的按钮获取存储的数据。 如何收拾烂摊子,继续我的下一个问题。在

提前谢谢你的帮助。在


Tags: 项目方法文本tkinter情况guibutton能力
1条回答
网友
1楼 · 发布于 2024-06-12 20:40:23

这是一个小例子和演示它有一切你需要启动你的程序。请参见代码内的注释:

enter image description here

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表达式的代码:

^{pr2}$

相关问题 更多 >