Tkinter有一个选项菜单会影响下一个

时间:2019-02-13 02:10:42

标签: python tkinter optionmenu

我想制作一个小程序,将目录中的文件夹列表并在选择菜单中列出,为此我使用了optionmenu,但我也看到人们也使用combomenu,因此如果它是更好的选择。 在项目菜单中做出选择后,我希望第二个菜单使用所选项目菜单内的文件夹进行更新。最后一步将是相同的,但我想这将是一个非常相似的过程。 还有一种打印选项菜单选择的好方法吗?

谢谢!

import os, sys
from tkinter import *
from tkinter import ttk



def findshots(*args):
    print("change")
    return 1




# -------- project selection ---------

currentprojects = './dummy/projects'
currentprojectslist = os.listdir(currentprojects)

# --------- shots list -------------------

projectselection = findshots()
currentshots = "./dummy/projects/{}/shots".format(currentprojectslist[projectselection])
currentshotslist = os.listdir(currentshots)




# ----------  script list -------------------

shotselection = 0
currentnk = "./dummy/projects/{}/shots/{}/nk".format(currentprojectslist[projectselection], currentshotslist[
    shotselection])
currentnklist = os.listdir(currentnk)


# ----------------------------------------------

# --------MAIN--------------



root = Tk()

root.geometry("1000x1000+800+100")
root.resizable(width=False, height=False)





# ------- project -----------
projectmenuvar = StringVar(root)
projectmenuvar.set(currentprojectslist[0])
projectmenuvar.trace("w", findshots)


projectmenuvar = OptionMenu(root, projectmenuvar, *currentprojectslist)
projectmenuvar.pack()





# ----------- shot -------------



shotsmenuvar = StringVar(root)
shotsmenuvar.set(currentshotslist[0])



shotsmenuvar = OptionMenu(root, shotsmenuvar, *currentshotslist)
shotsmenuvar.pack()


root.mainloop()

1 个答案:

答案 0 :(得分:0)

由于OptionMenu就像弹出菜单一样,只要更改shotsmenu,就可以更新projectmenu菜单项列表。以下是根据您的代码修改的代码:

from tkinter import *
import os

root = Tk()

# get project list
currentprojects = './dummy/projects'
currentprojectslist = os.listdir(currentprojects)

def findshots(*args):
    project = projectmenuvar.get()
    print('project changed:', project)
    # get shot list
    currentshots = '{}/{}/shots'.format(currentprojects, project)
    currentshotslist = os.listdir(currentshots)
    print(currentshotslist)
    # update the shotsmenu
    menu = shotsmenu['menu']
    menu.delete(0, 'end') # remove existing list
    for shot in currentshotslist:
        menu.add_command(label=shot, command=lambda val=shot: shotsmenuvar.set(val))
    # select the first shot
    shotsmenuvar.set(currentshotslist[0])

def on_shot_changed(*args):
    print('shot changed:', shotsmenuvar.get())

projectmenuvar = StringVar()
projectmenuvar.trace('w', findshots)
projectmenu = OptionMenu(root, projectmenuvar, *currentprojectslist)
projectmenu.config(width=15)
projectmenu.pack()

shotsmenuvar = StringVar()
shotsmenuvar.trace('w', on_shot_changed)
shotsmenu = OptionMenu(root, shotsmenuvar, ())
shotsmenu.config(width=15)
shotsmenu.pack()

# select the first project
projectmenuvar.set(currentprojectslist[0])

root.mainloop()