获取Entry的输入信息
使用get()
错误示范
from tkinter import *
root = Tk()
e= Entry(root)
e.pack()
entry = e.get()
root.mainloop()
print("Entered text:"+entry)
返回:
Entered text:
问题
使用get()时返回空值
原因
Your eventual second problem is that the text would anyhow be printed only after the mainloop finishes, i.e. you close the tkinter application.
在mainloop 结束后时打印才起作用
因此如果希望在运行程序时就调用Entry输入的内容,需要把get()同某一事件绑定
If you want to call get() when some text is entered (you probably do), you need to bind get() to an event.
If you want to print the contents of your Entry widget while your program is running, you need to schedule a callback. For example, you can listen to the pressing of the Return key as follows
通过回车键绑定callbackEntry的内容
import tkinter as tk
def on_change(e):
#打印输入信息
print(e.widget.get())
root = tk.Tk()
e = tk.Entry(root)
e.pack()
# Calling on_change when you press the return key
# get()必须绑定在一个事件中,这里使用的回车键
e.bind("<Return>", on_change)
root.mainloop()
解决方案来自stackoverflow
获取Listbox选中的信息
- 使用Listbox.curselection()获取所选项的 索引
- 以tupple形式返回,如果需要获取具体索引值,需访问tupple
- 同get()方法一眼,如果需要在程序运行过程中打印所选择的信息,需要将Listbox.curselection()同事件绑定
示例:
import tkinter as tk
def language_set(lang_set):
langs=['chi_sim','eng','fra','deu']
select_index=lang_set.widget.curselection()
#返回的是tupple,需要调用tupple的值
lang_index=select_index[0]
print("idex numebr {0}".format(select_index))
myWindow = tk.Tk()
myWindow.title('tkinter-Listbox')
myWindow.geometry('500x300')
lang_text=tk.StringVar()
lang_text.set(('简体中文','英语','法语','德语'))
lang_set = tk.Listbox(myWindow, selectmode=tk.BROWSE,listvariable=lang_text)
lang_set.pack(side='top')
lang_set.bind("<Return>", language_set)
myWindow.mainloop()