【发布时间】:2020-12-15 13:17:34
【问题描述】:
我在 Python 中几乎是新手,所以如果我的代码没有以正确的“pythonic 方式”编写,请原谅我...... 我想从列表框中保存用户的选择。该函数在 BES_library 模块中定义(我需要函数保留在模块中而不是脚本中!):
##BES_library
def quit(root, listbox, choice):
#get the user's choice
choice = listbox.get(listbox.curselection())
print(choice)
#quit the ListBox
root.destroy()
root.quit()
return choice
这是我的脚本:
import tkinter as tk
import BES_library as BES_lib
if __name__ == '__main__':
SheetsNames = ['Foglio1', 'Foglio2', 'Foglio3']
SheetName = 'lalala'
root = tk.Tk()
root.title("Select the worksheet to be opened")
listbox = tk.Listbox(root, selectmode= 'single')
for item in SheetsNames:
listbox.insert("end", item)
listbox.pack()
button = tk.Button(root, text='Select', command= lambda: BES_lib.quit(root, listbox, SheetName) )
button.pack()
root.geometry("450x300+120+120")
root.mainloop()
print(SheetName)
#now I want to work with the SheetName chosen by the user
用户应该从列表框中选择一个选项,然后单击“选择”按钮。单击按钮后,我想将他的选择作为字符串归因于变量并退出列表框。
问题是,我如何使用用户输入的内容?按钮不保存函数的返回值。
我也尝试了这段代码,但似乎没有任何改变:
import tkinter as tk
import BES_library as BES_lib
if __name__ == '__main__':
SheetsNames = ['Foglio1', 'Foglio2', 'Foglio3']
root = tk.Tk()
root.title("Select the worksheet to be opened")
SheetName = tk.StringVar()
listbox = tk.Listbox(root, selectmode= 'single')
for item in SheetsNames:
listbox.insert("end", item)
listbox.pack()
button = tk.Button(root, text='Select', command= lambda: BES_lib.quit(root, listbox, SheetName) )
button.pack()
root.geometry("450x300+120+120")
root.mainloop()
print(SheetName.get())
#now I want to work with the SheetName chosen by the user
【问题讨论】:
-
你知道 listbox.get('ANCHOR') 吗?
-
要销毁小部件,您可以使用
pack_forget()或place_forget(),具体取决于您使用的管理器
标签: python variables tkinter return