【问题标题】:Python tkinter passing input value within the same classPython tkinter 在同一个类中传递输入值
【发布时间】:2015-07-19 21:34:48
【问题描述】:

下面的大部分代码只是为了准确地复制问题,问题很可能是filenameaskopenfilenameI()printing(stringToPrint)或最后的if语句的交接。

目标

该程序的目标是在单击Print File Path 按钮时将文件路径简单地打印到控制台。

当前状态

当程序执行时,窗口会正确显示,它允许您在文件系统中选择一个文件。打开文件后,脚本似乎在执行自己的print 语句之前调用了printing 方法。当我打开另一个文件时,它会打印来自askopenfilename() 的唯一打印语句(这是正确的)。

但是,单击Print File Path 按钮似乎在任何阶段都不起作用。

一个示例输出是:

点击价值:no-file

askopenfilename 值:C:/Temp/AFTER_FIRST_OPEN.txt

askopenfilename 值:C:/Temp/AFTER_SECOND_OPEN.txt

代码

import Tkinter, Tkconstants, tkFileDialog

filename = 'no-file'

class TkApp(Tkinter.Frame):

    def __init__(self, root):

        Tkinter.Frame.__init__(self, root)
    
        # options for buttons
        button_opt = {'fill': Tkconstants.BOTH, 'padx': 5, 'pady': 5}
    
        # define buttons
        Tkinter.Button(self, text='Open File', command=self.askopenfilename).pack(**button_opt)
        Tkinter.Button(self, text='Print File Path', command=self.printing(filename)).pack(**button_opt)
        Tkinter.Button(self, text='Quit', command=self.quit).pack(**button_opt)
         
        # define options for opening or saving a file
        self.file_opt = options = {}
        options['defaultextension'] = '.twb'
        options['filetypes'] = [('All', '*')]
        options['initialdir'] = 'C:\\'
        options['parent'] = root
        options['title'] = 'Select a File'

    def askopenfilename(self):
        """Returns an opened file in read mode.
        This time the dialog just returns a filename and the file is opened by your own code.
        """
        global filename        
        # get filename
        filename = tkFileDialog.askopenfilename(**self.file_opt)
    
        # open file on your own
        if filename:
            print "askopenfilename value: " + filename
            return filename
            
    def printing(self, stringToPrint):
        print "Value on click: " + stringToPrint
   
    def quit(self):
        root.destroy()
        
 if __name__=='__main__':
        root = Tkinter.Tk()
        root.title("Path Printer")  
        TkApp(root).pack()
        root.mainloop()
        

【问题讨论】:

  • command=self.printing(filename) 参数实际上是在定义“打印文件路径”按钮时调用printing() 函数。

标签: python python-2.7 tkinter


【解决方案1】:

问题的根源在于您在创建按钮时调用了self.printing。解决方法很简单:将self.printing(filename) 改为self.printing,然后让self.printing 打印由self.askopenfilename 设置的属性。

例如:

class TkApp(Tkinter.Frame):
    def __init__(self, root):
        ...
        self.currentFile = None
        ...
        Tkinter.Button(self, text='Open File', command=self.askopenfilename)
        Tkinter.Button(self, text='Print File Path', command=self.printing)
        ...

    def askopenfilename(self):
        ...
        self.currentFile = tkFileDialog.askopenfilename(**self.file_opt)
        ...

    def printing(self):
        print "Value on click: " + self.currentFile

注意:从按钮调用的函数中的return 语句绝对没有任何作用。按钮的实际调用者忽略所有返回值。

【讨论】:

  • 非常感谢布莱恩!所以只是为了下次理解这一点,函数不必“返回”一个值才能被另一个函数拾取?定义一个变量就够了吗?
【解决方案2】:

我认为问题在于self.printing 函数在从按钮按下时调用时不能接受参数。这在许多 GUI 库中很常见。为了解决这个问题,我建议你将filename更改为self.filename,这样即使没有通过也可以从self.printing调用。

代码是:

import Tkinter, Tkconstants, tkFileDialog
class TkApp(Tkinter.Frame):
    def __init__(self, root):
        Tkinter.Frame.__init__(self, root)
        # options for buttons
        button_opt = {'fill': Tkconstants.BOTH, 'padx': 5, 'pady': 5}
        #moved initiation of filename to here so it will print if no file has been selected
        self.filename = 'no-file'
        # define buttons
        Tkinter.Button(self, text='Open File', command=self.askopenfilename).pack(**button_opt)
        Tkinter.Button(self, text='Print File Path', command=self.printing).pack(**button_opt) #not the removal of variable.
        Tkinter.Button(self, text='Quit', command=self.quit).pack(**button_opt)

        # define options for opening or saving a file
        self.file_opt = options = {}
        options['defaultextension'] = '.twb'
        options['filetypes'] = [('All', '*')]
        options['initialdir'] = 'C:\\'
        options['parent'] = root
        options['title'] = 'Select a File'

    def askopenfilename(self):
        """Returns an opened file in read mode.
        This time the dialog just returns a filename and the file is opened by your own code.
        """       
        # get filename - edited to be part of self
        self.filename = tkFileDialog.askopenfilename(**self.file_opt)

        # open file on your own
        if self.filename:
            print "askopenfilename value: " + self.filename
            return self.filename

    def printing(self):
        print "Value on click: " + self.filename

    def quit(self):
        root.destroy()

if __name__=='__main__':
        root = Tkinter.Tk()
        root.title("Path Printer")  
        TkApp(root).pack()
        root.mainloop()

【讨论】:

  • 谢谢!感谢您的帮助。
猜你喜欢
  • 2016-05-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-03
  • 2013-08-30
  • 1970-01-01
  • 2017-11-28
  • 2014-10-31
  • 2021-07-25
相关资源
最近更新 更多