默认情况下,按钮调用的函数的stdout在哪里?

时间:2013-02-18 14:28:07

标签: python tkinter

我试图打电话的功能如下:

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()

2 个答案:

答案 0 :(得分:2)

你所描述的不是stdout。当你使用print语句时,Stdout就是你要去的地方。您所描述的是函数的返回值。

Tkinter与所有其他python包一样 - 返回值返回给调用者。这种情况下的调用者是事件循环。事件循环不知道如何使用它调用的函数的返回值,因此它会抛出结果。

答案 1 :(得分: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()