我的Tkinter按钮命令仅循环执行一次

时间:2018-07-16 19:43:02

标签: python user-interface for-loop tkinter

我正在为使用Smartsheet API的工作编写程序。

这是我的代码:

import smartsheet
import logging
from tkinter import *

token  = "API KEY HERE"
matt_workspace = 7813091611174788
ss_client = smartsheet.Smartsheet(token) #Matt's workspace  

ss_client.errors_as_exceptions(True)

#for gethering workspaces

workspace_response = ss_client.Workspaces.list_workspaces(include_all=True)
all_workspaces = workspace_response.data
workspaces_name_and_id= []
for x in all_workspaces:
  workspaces_name_and_id.append(([str(x.name)], x.id))

selected_workspaces = []

def raise_frame(frame):
frame.tkraise()

#TODO set up UI root
import tkinter as tk                # python 3
from tkinter import font  as tkfont # python 3

def set_selected_workspaces(listbox):
    for x in listbox.curselection():
        selected_workspaces.append(workspaces_name_and_id[x])
        return selected_workspaces

class WorkspacesPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        label = tk.Label(self, text="Workspace Selection", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)

        wkdirections = tk.Label(self, 
            text = "1. Press the 'gather' button to gather all your available workspaces. \n 2. Select the workspaces with sheets you want to edit from the list. (Holding ctrl selects individual, holding shift selects en masse)")
        wkdirections.pack(side=RIGHT, anchor=CENTER)

        WorkspaceList = Listbox(self, selectmode=EXTENDED, width=100, height=50)
        WorkspaceList.pack(side=LEFT)

        for x in workspaces_name_and_id:
            WorkspaceList.insert(END, (x))

        button = tk.Button(self, text="Next", command=lambda: [controller.show_frame("FoldersPage"), set_selected_workspaces(WorkspaceList) ,print(selected_workspaces)], padx=20, pady=3)
        button.place(relx=0.975, rely=0.975, anchor=SE)

我从所包含的代码中删除了两个不必要的类(以使其变得比现在更混乱(包括主App / Tk应用))。

我的问题是我的“工作区选择”页面上“下一步”按钮中的set_selected_workplaces函数。

现在它正在用工作区及其各自的ID填充我的列表框。然后,当我单击下一步时,我希望它在列表框中选择的工作空间中循环,并将其添加到我的列表“ selected_workspaces”中,以供以后在程序中使用。

问题是,当我单击此按钮时,它仅在列表框中添加了第一个选择,因此使我相信它仅在我的for循环中经历了第一个循环。

有什么建议吗?请放心,我是编码方面的新手,我敢肯定它是一团糟。如果您需要任何澄清或更多的见解,请让我知道,我很困惑。

1 个答案:

答案 0 :(得分:2)

我想你回来太早了。代替这个

def set_selected_workspaces(listbox):
    for x in listbox.curselection():
        selected_workspaces.append(workspaces_name_and_id[x])
        return selected_workspaces

尝试

def set_selected_workspaces(listbox):
    for x in listbox.curselection():
        selected_workspaces.append(workspaces_name_and_id[x])
    return selected_workspaces

您的循环将在第一次迭代中返回,我认为这不是您想要的。