【问题标题】:python GUI button manipulates label textpython GUI按钮操作标签文本
【发布时间】:2015-07-27 12:39:41
【问题描述】:

嘿嘿,

我想用 Python 编写一个 GUI,将提示的单词(来自列表)与条目进行比较。这应该可以多次,所以我想制作一个按钮,删除条目和标签,然后提示列表中的下一个单词。 因此,单击按钮应操作标签上显示的文本。 巴士我该怎么做?

我的代码摘录是:

from Tkinter import *
i = 0  
vocablist = ['one', 'two', 'three']
np.random.shuffle(vocablist)
vocab = vocablist[i]
(...)

class simpleapp_tk(Tkinter.Tk):
    def __init__(self,parent):
        Tkinter.Tk.__init__(self,parent)
        self.parent = parent
        self.initialize()

    (...)

        self.label = Tkinter.Label(self, text=vocab,anchor="w") 
        self.label.grid(column=1,row=0)

    def clear_text():
        global i                
        self.entry.delete(0, 'end')
        i += 1 # don't know if this works!
        self.label.insert(0, vocab) # this does not work!

    button_next = Tkinter.Button(self,text=u"next", command=clear_text)
    button_next.grid(column=1,row=1)

if __name__ == "__main__":
    app = simpleapp_tk(None)
    app.title('rehearse vocabulary: translate!')
    app.mainloop()

我也试过

self.label.config(text=vocab)

而不是 .insert 函数。

我想知道是命令问题还是更新计数器然后自动将变量“vocab”更新为列表中的下一个元素不起作用?

感谢您的帮助!

【问题讨论】:

  • self.label.config(text=vocab) 是正确的解决方案。你说你试过了,但没有说你做了什么。
  • 有可能整个事情都不起作用,因为导入语句是from Tkinter import *,但随后使用Tkinter.Widgetname 访问它。
  • 感谢您的回答!我找到了使用 self.label.config(text=vocablist[i]) 而不是 vocab 的解决方案。这样,计数器就起作用了。
  • 你分配了vocab = vocablist[i],所以我不明白为什么text=vocab 不起作用...

标签: python user-interface button tkinter label


【解决方案1】:

尝试使用widget['attribute'] = 'value'。执行以下操作:

def action(event=None): # event in case you bind to a keypress
    entry.delete('0', END) # clear the entry
    label['text'] = "" # set label's widget text to ""
    next_word()

entry 是您的条目小部件,label 是您的标签,next_word() 提示输入下一个单词。

【讨论】:

    猜你喜欢
    • 2015-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 1970-01-01
    • 2012-10-14
    • 1970-01-01
    相关资源
    最近更新 更多