Python - Tkinter Label Output?

时光怂恿深爱的人放手 提交于 2021-01-29 02:00:36

问题


How would I take my entries from Tkinter, concatenate them, and display them in the Label below (next to 'Input Excepted: ')? I have only been able to display them input in the python console running behind the GUI. Is there a way my InputExcept variable can be shown in the Label widget?

from Tkinter import *

master = Tk()
master.geometry('200x90')
master.title('Input Test')

def UserName():
    usrE1 = usrE.get()
    usrN2 = usrN.get()
    InputExcept = usrE1 + " " + usrN2
    print InputExcept 

usrE = Entry(master, relief=SUNKEN)
usrE.pack()

usrN = Entry(master, relief=SUNKEN)
usrN.pack()

Btn1 = Button(text="Input", command=UserName)
Btn1.pack()

lbl = Label(text='Input Excepted: ')
lbl.pack()

master.mainloop()

回答1:


Two main steps to do:

  • You need to declare usrE, usrE and lbl as global variables inside your callback method.
  • You need to use config() method to update the text of lbl.

Program:

Here is the solution:

from Tkinter import *

master = Tk()
master.geometry('200x90')
master.title('Input Test')

def UserName():
    global usrE
    global usrN
    global lbl

    usrE1 = usrE.get()
    usrN2 = usrN.get()
    InputExcept = usrE1 + " " + usrN2
    print InputExcept 
    lbl.config(text='User expected:'+InputExcept)


usrE = Entry(master, relief=SUNKEN)
usrE.pack()

usrN = Entry(master, relief=SUNKEN)
usrN.pack()

Btn1 = Button(master, text="Input", command=UserName)
Btn1.pack()

lbl = Label(master)
lbl.pack()

master.mainloop()

Demo:

Running the program above will lead you to the expected result:

Note:

Do not forget to specify the parent widget (master) on which you draw the label and the button.



来源:https://stackoverflow.com/questions/38228932/python-tkinter-label-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!