我的一个变量正在打印,但另一个不在 tkinter 输入框中

问题描述

我正在尝试在 tkinter 中创建一个函数,我可以在其中打印出用户Entry 框中写入的内容。我可以打印出 ask_an_entry_get,但是当我尝试打印 what_is_answer_entry_get ,我的空位一无所获。

在这里找出问题所在。此外,我还使用 Entry 小部件以及 get() 函数获取用户的输入。

def answer_quizmaker_score():
    print(ask_an_entry_get)
    print(what_is_answer_entry_get)

我创建了很多全局变量,所以我可以在我的代码中使用它们。

global what_is_answer_entry    
what_is_answer_entry = Entry(root4)
what_is_answer_entry.pack()

然后我使用 get() 函数来检索用户输入的内容

global what_is_answer_entry_get
what_is_answer_entry_get = what_is_answer_entry.get()

这是我为 ask_an_entry_getwhat_is_answer_entry_get 所做的确切过程。但是由于某种原因,只打印了 ask_an_entry_get,而 what_is_answer_entry_get 在控制台中什么也不打印。

解决方法

from tkinter import *


root = Tk()
root.geometry("500x500")

txt1 = StringVar()
txt2 = StringVar()

def txt_printer():
    print(txt1.get())
    print(txt2.get())

x = Entry(root,textvariable=txt1,width=20)
x.place(x=0,y=0)

y = Entry(root,textvariable=txt2,width=20)
y.place(x=0,y=50)

btn_print = Button(root,text="print",command=txt_printer)
btn_print.place(x=0,y=100)

# Or if you want to show the txt on window then:

def txt_on_window():
    lb1 = Label(root,text=txt1.get())
    lb1.place(x=0,y=200)
    lb2 = Label(root,text=txt2.get())
    lb2.place(x=0,y=235)

btn_print_on_window = Button(root,text="print on screen",command=txt_on_window)
btn_print_on_window.place(x=0,y=150)

root.mainloop()