Tkinter Entry的get函数不返回任何内容

时间:2019-12-24 19:19:16

标签: python-3.x tkinter tkinter-entry

我正在尝试使用Entry小部件来获取用户的数据,然后进行打印。 Why is Tkinter Entry's get function returning nothing? 这对我没有帮助。

这是我的代码

message = ''
    # start_chatting function
    def start_chatting ():
        global message
        master2 = tk.Tk()
        master2.geometry("1280x720")
        master2.title("Messenger")
        label = tk.Label(master2, text = "Messenger!!!",bg = '#1e00ff',fg ='yellow',width = 35, height = 5).place(x = 500, y = 0)
        username_label = tk.Label(master2,text = usernames[position_counter],bg = '#91806d',fg ='white',width = 10, height = 2).place(x = 0, y = 100)
        v = StringVar()
        L1 = Label(master2, text = "Type your message : ").place(x=0, y = 680)
        e = Entry(master2,textvariable = v)
        e.insert(END, '')
        e.pack()
        e.place(x = 115, y = 680)
        submit_button = Button(master2,text = "Submit",command = submit_f).place(x = 200, y = 680)
        message = message+ v.get()
        master2.mainloop()

#submit_f function  
def submit_f ():
    global message
    print(message)

请记住,这是我的代码的一部分,而不是全部。
预先感谢!

1 个答案:

答案 0 :(得分:1)

该函数不会打印任何内容,因为您在定义输入框的当前函数中更改了message值。

因此,当您编写v.get()时,通常会返回一个空文本。每次按下message按钮时,都需要调用submit变量。因此,应在message函数中更改submit_f()变量。

这是解决方案,

import tkinter
from tkinter import *

message = ''
    # start_chatting function
def start_chatting ():
    global v
    master2 = Tk()
    master2.geometry("1280x720")
    master2.title("Messenger")
    label = Label(master2, text = "Messenger!!!",bg = '#1e00ff',fg ='yellow',width = 35, height = 5).place(x = 500, y = 0)
    username_label = Label(master2,text = usernames[position_counter],bg = '#91806d',fg ='white',width = 10, height = 2).place(x = 0, y = 100)
    L1 = Label(master2, text = "Type your message : ").place(x=0, y = 680)
    v = StringVar()
    e = Entry(master2,textvariable = v)
    e.insert(END, '')
    e.pack()
    e.place(x = 115, y = 680)
    submit_button = Button(master2,text = "Submit",command = submit_f).place(x = 200, y = 680)
    master2.mainloop()

#submit_f function
def submit_f ():
    global message
    message = message + " " + v.get()
    print(message)

start_chatting()