第二个函数传递Tkinter Python 2.7时的选项菜单更改

第二个函数传递Tkinter Python 2.7时的选项菜单更改,python,tkinter,optionmenu,Python,Tkinter,Optionmenu,我遇到的问题是,在单击“回车”按钮之前,下面的功能在第一次通过时可以很好地在选项菜单顶部显示所选值: 但是,在第二次传递和以后传递到功能时,在按下“回车”按钮之前,所选值不会显示在选项菜单的顶部(尽管如果选中,将使用该值): 代码是: def load_create_list(self): self.app = Toplevel(self.parent) self.parent.withdraw() self.app.title("Rgs2") self.

我遇到的问题是,在单击“回车”按钮之前,下面的功能在第一次通过时可以很好地在选项菜单顶部显示所选值:

但是,在第二次传递和以后传递到功能时,在按下“回车”按钮之前,所选值不会显示在选项菜单的顶部(尽管如果选中,将使用该值):

代码是:

def load_create_list(self):

    self.app = Toplevel(self.parent)
    self.parent.withdraw()
    self.app.title("Rgs2")

    self.student = []
    self.student1=[]
    self.gs1=0
    self.ng1=0
    options = ["2", "3", "4", "5", "6", "7"]


    self.results=[]
    self.ngg=StringVar() #for the option menu widget the variable must be a stringVar not a normal string, int etc.

    self.ng = Label(self.app, text="Number of groups")
    self.ng.grid(row=2, column=0)
    self.ngg.set("3")
    self.ng1 = OptionMenu(self.app, self.ngg, *options)

    self.ng1.grid(row=2, column=1, ipadx=10)


    for i in range(0,len(self.x3)):
        self.L1 = Label(self.app,text="Student")
        self.L1.grid(row=i+4, column=0)
        self.en = Entry(self.app)
        self.en.insert(END, self.x3[i])
        self.en.grid(row=i+4, column=1)
        self.student.append(self.en)

    self.el = int(len(self.student)+1)

    for h in range(self.el,self.el+5):

        self.L2 = Label(self.app,text="Student")
        self.L2.grid(row=h+4, column=0)
        self.em = Entry(self.app)
        self.em.grid(row=h+4, column=1)
        self.student.append(self.em)

    button=Button(self.app,text="enter",command=lambda : self.hallo2()).grid(row=h+7,column=0)
    button=Button(self.app,text="Save List",command=lambda : self.save_list2()).grid(row=h+7,column=1)
我已经尝试了所有方法,但无法理解是什么导致了这些问题。任何帮助都将不胜感激。似乎是非常奇怪的行为可能是功能之外的东西导致了问题

完整代码为:

from Tkinter import *
from tkFileDialog import askopenfile


class main_menu:

    def __init__(self, parent):

        self.myParent = parent
        self.myContainer1 = Frame(parent)
        parent.title("Random Group Sorter")
        self.myContainer1.pack()

        self.button1 = Button(self.myContainer1, command = lambda : self.hope())               
        self.button1.configure(text="Create List", height = 1, width = 20, font=("Arial", 16))
        self.button1.pack(side=TOP)
        self.button1.focus_force()

        self.button3 = Button(self.myContainer1, command = lambda : self.hope1())
        self.button3.configure(text="Load List", height = 1, width = 20, font=("Arial", 16))
        self.button3.pack(side=TOP)     

        self.button2 = Button(self.myContainer1, command = lambda : exit(), )  
        self.button2.configure(text="Exit",height = 1, width = 20, font=("Arial", 16))
        self.button2.pack(side=TOP)

    def hope(self):
        self.myParent.destroy()
        create_list()

    def hope1(self):
        self.myParent.destroy()
        load_list()

class create_list():

    def __init__(self):


        parent = Tk()


        self.parent=parent
        self.student = []
        self.student1 =[] 
        self.student2 =[] 
        self.fake_student = []     
        self.results=[]
        self.ngg = StringVar()# for the option menu widget the variable must be a stringVar not a normal string, int etc.

        self.ng = Label(text="Number of groups")
        self.ng.grid(row=2, column=0)

        self.ng = OptionMenu(parent, self.ngg, "2", "3", "4", "5","6")
        self.ng.grid(row=2, column=1)

        for i in range(3,21):
            self.L1 = Label(text="Student")
            self.L1.grid(sticky=E)
            self.en = Entry(parent)

            self.en.grid(row=i, column=1)
            self.student.append(self.en)

        button=Button(parent,text="Enter",command=lambda : self.hallo()).grid(row=23,column=0)
        button=Button(parent,text="Save List",command=lambda : self.save_list()).grid(row=23,column=1)

        parent.mainloop()


    def hallo(self):

        self.gs1 = int(len(self.student))

        self.ng1 = int(self.ngg.get())# still need to use .get even though a stringvar

        for entry in self.student:
            self.student1.append(entry.get())
        self.student1 = filter(None, self.student1) 

        for i in self.student1:# this is added as there are duplicate entries in the student list if saved
            if i not in self.student2:
                self.student2.append(i)
        self.parent.destroy()

        lis_an(self.student2,self.ng1)

    def save_list(self):


        for entry in self.student:
            self.student1.append(entry.get())
        self.student1 = filter(None, self.student1) 

        import tkFileDialog
        root = Tk()
        root.withdraw()
        file_name = tkFileDialog.asksaveasfile(parent=root)
        root.destroy() 

        print >>file_name, "\n"
        print >>file_name, "\n".join(self.student1)

        file_name.close()


class load_list:
    def __init__(self):
        self.x = []
        self.x3 = []
        self.load_clean()
        self.root = Tk()


    def load_clean(self):#option to load an already created file, cleans unwanted info from the list

        import tkFileDialog
        root = Tk()
        root.withdraw()
        file_name = tkFileDialog.askopenfile(parent=root)
        root.destroy()

        self.x = file_name.readlines()
        file_name.close()
        x2 =self.x[:]
        for z in self.x:
            if z [0:6]== "Random" or z == '\n' or z[0:5] == "Group":
                x2.remove(z)     

        for c in range (0,len(x2)):
            v = x2[c].rstrip()# this strip spaces and \n from each list item and returns the cleaned up string
            self.x3.append(v)

        self.load_create_list()   

    def load_create_list(self):
        parent = Tk()

        self.parent=parent
        self.student = []
        self.student1=[]
        self.gs1=0
        self.ng1=0



        self.results=[]
        self.ngg = StringVar()# for the option menu widget the variable must be a stringVar not a normal string, int etc.

        self.ng = Label(text="Number of groups")
        self.ng.grid(row=2, column=0)

        self.ng = OptionMenu(parent, self.ngg, "2", "3", "4", "5", "6")
        self.ng.grid(row=2, column=1)



        for i in range(0,len(self.x3)):
            self.L1 = Label(text="Student")
            self.L1.grid(row=i+3, column=0)
            self.en = Entry(parent)
            self.en.insert(END, self.x3[i])
            self.en.grid(row=i+3, column=1)
            self.student.append(self.en)

        self.el = int(len(self.student)+1)

        for h in range(self.el,self.el+5):

            self.L2 = Label(text="Student")
            self.L2.grid(row=h+3, column=0)
            self.em = Entry(parent)
            self.em.grid(row=h+3, column=1)
            self.student.append(self.em)

        button=Button(parent,text="enter",command=lambda : self.hallo2()).grid(row=h+6,column=0)
        button=Button(parent,text="Save List",command=lambda : self.save_list2()).grid(row=h+6,column=1)
        parent.mainloop()   

    def hallo2(self):
        self.student2= []
        self.gs1 = int(len(self.student))
        self.ng1 = int(self.ngg.get())# still need to use .get even though a stringvar
        for entry in self.student:
            self.student1.append(entry.get())
        self.student1 = filter(None, self.student1) 
        for i in self.student1:# this is added as there are duplicate entries in the student list if saved
            if i not in self.student2:
                self.student2.append(i)
        self.parent.destroy()

        lis_an(self.student2,self.ng1)

    def save_list2(self):
        for entry in self.student:
            self.student1.append(entry.get())
        self.student1 = filter(None, self.student1) 

        import tkFileDialog
        root = Tk()
        root.withdraw()
        file_name = tkFileDialog.asksaveasfile(parent=root)
        root.destroy() 

        print >>file_name, "\n"
        print >>file_name, "\n".join(self.student1)

        file_name.close()




class lis_an:        
     def __init__(self,student1,ng1):
        self.student1 = student1
        self.ng1=ng1
        self.results = []
        self.randomList()

     def randomList(self): # this creates a random list of students on the course
        import random
        studentb = self.student1[:]# this is added as otherwise the student list is overwritten

        studentc = [] 
        for i in range(len(studentb)): 
            element = random.choice(studentb) 
            studentb.remove(element) 
            studentc.append(element) 
        self.student1 = studentc

        self.partition()

     def partition(self): # this creates sub list of the student list containing the groups of students

        increment = len(self.student1) / float(self.ng1)
        last = 0
        i = 1
        while last < len(self.student1):
            idx = int(round(increment * i))
            self.results.append(self.student1[last:idx])
            last = idx
            i += 1

        output(self.results, self.ng1)  

class output:
    def __init__(self, student, ng1):

        self.ng1 = ng1
        self.student = student
        self.parent = Tk()


        for item1 in range (0,len(self.student)):

            test1 = "Group " + str(item1+1)+ ":"
            v = Label(self.parent, text=test1, font=("Arial", 13))
            test = "\n".join(self.student[item1])

            w = Label(self.parent, text=test, justify = LEFT, font=("Arial", 12))
            v.pack(side="top", anchor="w")
            w.pack(side="top", anchor="w")

        button=Button(self.parent,text="Repeat",command=lambda : self.join_list()).pack(side="top", anchor="w")
        button=Button(self.parent,text="Main Menu",command=lambda : self.menu_link()).pack(side="top", anchor="w")

        mainloop()

    def join_list(self):#this function creates a new undivided version of student to feed back to lis_an
        self.parent.destroy()
        self.student = [j for i in self.student for j in i] 
        lis_an(self.student,self.ng1)

    def menu_link(self):#destroys the parent frame and returns back to main menu
        self.parent.destroy()
        main()

def main():
    parent = Tk()
    myapp = main_menu(parent)
    parent.mainloop()

main()
将导致错误,并且

self.ngg = StringVar(self.app)

解决了这个问题。不太清楚为什么在第二次和后续使用该函数时会出现这种情况,但在第一次使用时不会出现这种情况。

您所说的“第二次使用”是什么意思?您是否多次调用该函数?为什么要在函数内部调用
mainloop
,或者这是该站点的代码格式错误?请出示完整的最小工作程序:第二次通过表示函数的第二次运行,即第二次使用。抱歉,main.loop被意外复制。完整的代码相当大,您需要全部查看吗?不,我们不需要查看完整的代码。请阅读。我们希望您用足够的代码创建一个新程序来说明这个问题。您90%的代码可能与您试图解决的问题完全无关。我已多次尝试(单独)运行该函数,但似乎无法重现相同的问题,因此它一定是函数之外的问题。我似乎无法找到问题所在,也不知道它可能在哪里,所以我提供了完整的代码。我只学了几周python。谢谢。按原样开始你的程序。删除一行代码。问题是否仍然存在?删除另一行?问题还在吗?删除另一行。新问题?把那条线放回去,再挑一条线。这不仅仅是为了让我们的生活更轻松,它还帮助你更好地理解这个问题。例如,在main中有三个按钮——您真的需要三个按钮来导致这种不良行为吗?关于
save\u list
,这是导致问题的原因吗<代码>保存列表2?这是学习过程的一部分。
self.ngg = StringVar(self.app)