【问题标题】:Receiveing input from Python's tkinter entry widget and displaying it in a label从 Python tkinter 条目小部件接收输入并将其显示在标签中
【发布时间】:2014-12-30 01:20:04
【问题描述】:

我目前正在使用的程序需要用户输入才能显示在程序窗口上。我在互联网和 stackoverflow 上都进行了研究,发现了几种解决我的问题的方法,但似乎都没有奏效。我的目标是通过 Python 的 tkinter 条目小部件接收用户的输入,并在新标签中显示结果,同时取出我的初始标签和输入框,但是,程序拒绝了我的答案尝试。

您对我实现目标有什么策略、代码行/库或建议?

我现有的解决方案:

.get()
textvariable=self.entdat

现有代码如下:

from Tkinter import *
import time

class Input(Frame):

  def __init__(self, parent=None, **kw):
    Frame.__init__(self, parent, background="white")
    self.parent = parent
    self.initUI()
    self.entdat = StringVar
    self.timestr = StringVar()
    self.makeWidgets()

def makeWidgets(self):
    self.ol = Label(text="Objective:")
    self.ol.pack(side=TOP)
    self.ew = Entry()
    self.ew.pack(side=TOP)
    self.b = Button(text="OK", command=self.clicked)
    self.b.pack(side=TOP)

def clicked(self):
    self.entdat = self.ew.get()
    self.dat = Label(textvariable=self.ew.get())
    self.dat.pack(side=TOP)
    self.hide_Widget()


def hide_Widget(event):
    event.ew.pack_forget()
    event.ol.pack_forget()
    event.b.pack_forget()

def main():
root = Tk()
root.geometry("240x135+25+50")
tm = Input(root)
tm.pack(side=TOP)

root.mainloop()

if __name__ == '__main__':
    main()

【问题讨论】:

  • 什么是self.initUI()?它没有在您提供的代码中定义。
  • 很抱歉。我只包括了包含问题的程序部分。 self.intitUI() 将 parent.title 设置为“Input”。

标签: python tkinter label python-2.6 tkinter-entry


【解决方案1】:

我修改了您的代码,使其至少可以执行,并希望以您想要的方式执行。

from Tkinter import *

class Input(Frame):
    def __init__(self, parent=None, **kw):
        Frame.__init__(self, parent, background="white")
        self.parent = parent
        self.entdat = StringVar()
        self.makeWidgets()

    def makeWidgets(self):
        self.ol = Label(text="Objective:")
        self.ol.pack(side=TOP)
        self.ew = Entry(textvariable=self.entdat)
        self.ew.pack(side=TOP)
        self.b = Button(text="OK", command=self.clicked)
        self.b.pack(side=TOP)

    def clicked(self):
        self.dat = Label(self, textvariable=self.entdat )
        self.dat.pack(side=TOP)
        self.distroy_Widget()


    def distroy_Widget(self):
        self.ew.destroy()
        self.ol.destroy()
        self.b.destroy()

def main():
    root = Tk()
    root.geometry("240x135+25+50")
    tm = Input(root)
    tm.pack(side=TOP)

    root.mainloop()

if __name__ == '__main__':
    main()

希望对你有帮助。

【讨论】:

  • 非常感谢,这正是我想要的。你愿意花时间来做这件事对我来说意义重大。现在,它又开始为我编程了! :-)
  • @Rick_Roll 不用担心。很高兴我能帮上忙。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-01
  • 1970-01-01
相关资源
最近更新 更多