Python:如何将消息窗口小部件的文本更改为用户输入

时间:2016-09-06 16:55:27

标签: python tkinter

所以我制作了一个程序,要求用户输入一个值。我想通过消息小部件(或标签小部件)显示值,并在输入新输入时更新。

def Enter():
    s = v.get()
    print (v.get())

    e.delete(0, END)
    e.insert(0, "")

#Code, Code, Code
...

# Area To Enter Text
v = StringVar()
e = Entry(root, textvariable=v)
e.pack()

m = Message(root, text = "Your Input")
m.pack()

# Enter Button
b = Button(root, text="OK", command=Enter)
b.pack()

是否有办法让v的变量替换Message Widget的文本?

注意:

如果我用text替换textvariable,它会在按下每个字符键后更新文本,我需要在用户按下按钮时更新文本。

我的完整代码:

from tkinter import *
import os

# All Functions Below
def callback():
    print ("HI")

def Exit():
    os._exit(0)

def Enter():
    s = e.get()
    print (e.get())
    m.configure(text=s)
    e.delete(0, END)
    e.insert(0, "")

def Population():
    root = Tk

    root.mainloop()

def SurvivalRate():
    root = Tk

    root.mainloop()

def BirthRate():
    root = Tk

    root.mainloop()

def NewGen():
    root = Tk

    root.mainloop()

root = Tk()


generation = 0

menubar = Menu(root)
menubar.add_command(label="Hello!", command=callback)
menubar.add_command(label="Quit!", command=Exit)


# Area To Enter Text
e = Entry(root)
e.pack()

m = Message(root, text = e)
m.pack()

# Enter Button
b = Button(root, text="OK", command=Enter)
b.pack()

Pop = Button(root, text="Population", command=Population)
Pop.pack()

1 个答案:

答案 0 :(得分:4)

只需添加:

m.configure(text=s) 

到你的职能部门:

def Enter():
    s = v.get()
    print (v.get())
    m.configure(text=s)
    e.delete(0, END)
    e.insert(0, "")

作为旁注,您不一定需要StringVar()。下面的代码将完全相同:

def Enter():
    s = e.get()
    m.configure(text=s)
    e.delete(0, END)
    e.insert(0, "")

#Code, Code, Code
...

# Area To Enter Text
e = Entry(root)
e.pack()

m = Message(root, text = "Your Input")
m.pack()

# Enter Button
b = Button(root, text="OK", command=Enter)
b.pack()

root.mainloop()