我在python的Tkinter中做了一些optionMenu,我想得到用户选择的值。我用过变量获取()在方法中,该方法在单击项时调用,但我没有获得正确的值。我一直得到“status”,这是我最初分配给var的值,使用变量集(). 在单击浏览按钮后,菜单中的项目将被初始化,因此我用一个名为browser的方法填充了列表。在每个项目的command属性中,我调用justamethod来打印值。这是我的代码:
self.varLoc= StringVar(master)
self.varLoc.set("status")
self.varColumn= StringVar(master)
self.varColumn.set("")
self.locationColumn= Label(master,text="Select a column as a location indicator", font=("Helvetica", 12))
self.columnLabel= Label(master,text="Select a column to process", font=("Helvetica", 12))
global locationOption
global columnOption
columnOption= OptionMenu (master, self.varColumn,"",*columnList)
locationOption= OptionMenu (master, self.varLoc,"",*columnList)
self.locationColumn.grid (row=5, column=1, pady=(20,0), sticky=W, padx=(5,0))
locationOption.grid (row=5, column=3, pady=(20,0))
def browser (selft):
filename = askopenfilename()
#open_file(filename)
t=threading.Thread (target=open_file, args=(filename, ))
#t=thread.start_new_thread (open_file,(filename, )) # create a new thread to handle the process of opening the file.
# we must then send the file name to the function that reads it somehow.
t.start()
t.join() #I use join because if I didn't,next lines will execute before open_file is completed, this will make columnList empty and the code will not execute.
opt=columnOption.children ['menu']
optLoc= locationOption.children ['menu']
optLoc.entryconfig (0,label= columnList [0], command=selft.justamethod)
opt.entryconfig (0, label= columnList [0], command=selft.justamethod)
for i in range(1,len (columnList)):
opt.add_command (label=columnList[i], command=selft.justamethod)
optLoc.add_command (label=columnList[i], command=selft.justamethod)
def justamethod (self):
print("method is called")
print(self.varLoc.get())
window= Tk () #main window.
starter= Interface (window)
window.mainloop() #keep the window open until the user decides to close it.
有人能告诉我如何得到所选项目的价值吗?在
谢谢。在
justamethod
函数除了varLoc
的初始化值外不会打印任何内容,因为您不会对它执行任何操作。在由于菜单选项不能接受
variable
参数,因此与其尝试为所有菜单选项更新一个变量的值,不如为每个菜单按钮传递一些任意值?在示例:
(示例直接取自this tutorial。)
在您的代码中,由于您使用计数器
i
在for
循环中生成菜单按钮,所以您可以简单地执行类似于command = lambda: self.justamethod(i)
的操作,然后在justamethod
内打印出所传递的i
参数,以了解我的意思。在我希望这有助于您解决您的问题,因为我无法真正修改您提供的代码来提供解决方案,因为它无法使用。在
相关问题 更多 >
编程相关推荐