我是tkinter / python的新手,我担心我的问题很简单,到目前为止还没有人对此感到愚蠢。我创建了以下脚本:
import tkinter as tk
from tkinter import *
class example(tk.Frame):
#Initialize class
def __init__(self,parent):
tk.Frame.__init__(self, parent)
self.listbox = tk.Listbox(self,selectmode=SINGLE)
self.listbox.pack(expand=True)
self.button = tk.Button(self,text="Confirm Selection",command=self.selection)
self.button.pack(side="bottom",fill="both",expand=True)
self.string = tk.StringVar()
#Add variables
for i in ['A','B','C']:
self.listbox.insert(END,i)
#Selection method
def selection(self):
index = self.listbox.curselection()[0]
name = ['A','B','C'][index]
self.string = name
print(self.string)
#Main script
root = tk.Tk()
example(root).pack(expand=True)
root.mainloop()
我可以在
中打印列表选择的结果def selection(self)
但是,我不知道如何在脚本继续运行时拉出并进一步使用。例如,如果要继续我的#Main脚本,我想做类似的事情:
letter = '''results of listbox selection'''
作为奖励,我很难销毁列表框,只有列表和按钮被删除我尝试过的方法。
谢谢大家
答案 0 :(得分:0)
我已经解决了我的问题。我没有意识到在返回值后如何正确使用wait_window
函数来恢复脚本。
我已经进行了大幅修改,以下内容符合我的目的:
`
来自tkinter import *
class ListBoxChoice(object):
def __init__(self, master=None, title=None, message=None, list=[]):
self.master = master
self.value = None
self.list = list[:]
self.modalPane = Toplevel(self.master)
self.modalPane.transient(self.master)
self.modalPane.grab_set()
self.modalPane.bind("<Return>", self._choose)
self.modalPane.bind("<Escape>", self._cancel)
if title:
self.modalPane.title(title)
if message:
Label(self.modalPane, text=message).pack(padx=1, pady=1)
listFrame = Frame(self.modalPane)
listFrame.pack(side=TOP, padx=5, pady=5)
scrollBar = Scrollbar(listFrame)
scrollBar.pack(side=RIGHT, fill=Y)
self.listBox = Listbox(listFrame, selectmode=SINGLE)
self.listBox.pack(side=LEFT, fill=Y)
scrollBar.config(command=self.listBox.yview)
self.listBox.config(yscrollcommand=scrollBar.set)
self.list.sort()
for item in self.list:
self.listBox.insert(END, item)
buttonFrame = Frame(self.modalPane)
buttonFrame.pack(side=BOTTOM)
chooseButton = Button(buttonFrame, text="Choose", command=self._choose)
chooseButton.pack()
cancelButton = Button(buttonFrame, text="Cancel", command=self._cancel)
cancelButton.pack(side=RIGHT)
def _choose(self, event=None):
try:
firstIndex = self.listBox.curselection()[0]
self.value = self.list[int(firstIndex)]
except IndexError:
self.value = None
self.modalPane.destroy()
def _cancel(self, event=None):
self.modalPane.destroy()
def returnValue(self):
self.master.wait_window(self.modalPane)
return self.value
self.modalPane.destroy()
if __name__ == '__main__':
root = Tk()
list = ['A','B','C']
returnValue = ListBoxChoice(root, "Pick Letter", "Pick one of these crazy random numbers", list).returnValue()
print(returnValue)'
我现在唯一的问题是在运行脚本时我打开了2个对话框。我敢肯定它与我如何绑定所有内容有关,但仍在排序。
干杯