0

我试图调用的函数如下:

def numberitems(self):
    files = len(os.listdir(self.directory))
    print (items)

按钮的代码:

button = Button(text = 'Count Items', command = Class1.numberItems()).pack()

我在哪里导入课程:

from class import Class1

定义目录:

def loadDirectory():
    return Class1(filedialog.askdirectory())
    dir = loadDirectory()
4

2 回答 2

2

您所描述的不是标准输出。print当您使用该语句时,标准输出是事情的去向。您所描述的是函数的返回值。

Tkinter 就像所有其他 python 包一样——返回值被返回给调用者。这种情况下的调用者是事件循环。事件循环不知道如何使用它调用的函数的返回值,所以它把结果扔掉了。

于 2013-02-18T14:33:30.313 回答
0

根据 tcaswell 给出的上下文,您的主代码中有几个错误。

假设一个chrome.py是:

class Chrome:
    directory = ""

    def __init__(self, directory):
        self.directory = directory

    def numberOfFiles(self):
        return len(os.listdir(self.directory))

要调用它来打印 的结果numberOfFiles,您需要执行与此类似的操作:

文件:q_14938600.py

import os
from chrome import Chrome
from Tkinter import *

class App(object):
    """Basic TK App."""

    def __init__(self, parent):
        f = Frame(parent)
        f.pack(padx=15, pady=15)

        # Here I initiate the Chrome class, and set its directory. I'm using os.getcwd() as an example.
        self.ch = Chrome(os.getcwd())

        # Here I tell the button what to call when clicked. Note I'm NOT passing arguments to the function, just a reference.
        button = Button(f, text='Count Files', command=self.printFileCount)
        button.pack(side=BOTTOM)

    def printFileCount(self):
        # And here, I print the output of ch.numberOfFiles, which was defined in the Chrome class
        print(self.ch.numberOfFiles())

if __name__ == "__main__":
    # This is just standard app stuff
    root = Tk()
    root.title('q_14938600')
    app = App(root)
    root.mainloop()
于 2013-02-18T15:32:18.813 回答