简体   繁体   English

python / tkinter在按下按钮时将单词的各个字母添加到标签中

[英]python/tkinter add the individual letters of a word to a label on button press

from tkinter import *

# Create a window
spell_window = Tk()

# Give the window a title
spell_window.title('Spell Table')


table_Var = StringVar()

## table = ['T', 'a', 'b', 'l', 'e'] ## I think it needs to move through a list???

def spell_table():
    s_table = monty_Var.get()
    s_table += 'T' #Currently adds a 'T' each time the button is pressed
    monty_Var.set(s_table)



the_label = Label(spell_window, width = 10, textvariable = table_Var,
                  font = ('Arial', 30), bg = 'red')

the_button = Button(spell_window, text = 'Next letter', command = spell_table)

the_label.pack(padx = 0, pady = 0)

the_button.pack(padx = 40, pady = 0)

So basically i have created the label and button and need to spell out the word Table by pressing the Next letter button. 因此,基本上我已经创建了标签和按钮,并且需要通过按下一个字母按钮来拼写单词Table。 Just not sure how to make it move through the table list and add them to label. 只是不确定如何使它在表列表中移动并将其添加到标签。

Here is the fixed code: 这是固定代码:

from tkinter import *

spell_window = Tk()

spell_window.title('Spell Table')

table = ['T', 'a', 'b', 'l', 'e']
count = 1

def spell_table():
   global count, table
   the_label.config(text=table[:count])

   if count < len(table):
      count += 1



the_label = Label(spell_window, width = 10, text = "", font = ('Arial', 30), bg = 'red')

the_button = Button(spell_window, text = 'Next letter', command = spell_table)

the_label.pack(padx = 0, pady = 0)

the_button.pack(padx = 40, pady = 0)

spell_window.mainloop()

I deleted useless variables and added a 'count' variable that increases with each click. 我删除了无用的变量,并添加了一个“计数”变量,该变量随着每次点击而增加。 And yes, you did need a list for that, a tuple would do too. 是的,您确实需要一个列表,一个元组也可以。 I changed "the_label"'s text from 我更改了“ the_label”的文本

'textvariable = ' to 'text = ""'.

I also sliced the list according to the 'count'. 我还根据“计数”对列表进行了切片。 [:count] = anything before count's index value. [:count] =计数索引值之前的任何内容。 also the if statement is there just to be efficient, because we don't need to allocate more space to the variable after it exceeded the index value of the 'table' list. 还有if语句只是为了提高效率,因为在变量超出“表”列表的索引值之后,我们无需为变量分配更多空间。 You were also missing a 你也错过了

spell_window.mainloop()

at the end. 在末尾。 Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM