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

问题描述 投票:0回答:1

我想创建一个小程序,它将获取目录中的文件夹列表,并将它们列在选择菜单中,我已经使用了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()
python tkinter optionmenu
1个回答
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()
© www.soinside.com 2019 - 2024. All rights reserved.