问题
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
andlbl
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