python 2.7 Tk更改标签以携带打开文件中的文件名

标签 python tkinter

我在 python 2.7 中有这段代码,使用 tkinterFrame 上创建一个 Button 来打开文件。它下面有一个Label。我试图做到这一点,一旦文件打开,标签就会在Label上打印路径“file1.name”或其他内容,如果您打开一个新文件,它会更改该路径再次标签

此外,我敢打赌,有一种比我在这里使用 global 更好的方法在函数之间移动数据,但现在我并不担心。

我必须在函数之间移动打开的文件中的数据,以便我可以混合数据并保存到新文件中。代码是:

from Tkinter import *
import Tkinter
import tkFileDialog
import tkMessageBox
root = Tkinter.Tk()
global rfile1
global rfile2
rfile1 = ""
rfile2 = ""
class Application(Frame):

    def __init__(self, master = None):
        Frame.__init__(self, master)
        self.grid()
        self.createWidgets1()
        self.createLabels1()
        self.createWidgets2()
        self.createLabels2()

    def createWidgets1(self):
        self.oButton = Button(self, text = "open1", command = self.openfile1)
        self.oButton.grid()

    def createLabels1(self):
        self.oLabel = Label(self, text = "whoops")
        self.oLabel.grid()

    def createWidgets2(self):
        self.oButton = Button(self, text = "open2", command= self.openfile2)
        self.oButton.grid()

    def createLabels2(self):
        self.oLabel2 = Label(self, text = "whoops2")
        self.oLabel2.grid()

    def openfile1(self):
        file1 = tkFileDialog.askopenfile(title = "choose a file, *****", parent=root, mode = 'rb')

        rfile1 = file1.read()
        tkMessageBox.showinfo("oy", rfile1, parent=root)

    def openfile2(self):
        file2 = tkFileDialog.askopenfile(parent=root, mode='rb')

        rfile2 = file2.read()
        tkMessageBox.showinfo("hola", rfile2, parent=root)

app = Application()
app.master.title("whiggy whompus")
app.mainloop()

最佳答案

如果我理解正确,你想要类似的东西(未经测试):

def openfile1(self):
    file1 = tkFileDialog.askopenfile(title = "choose a file, *****", parent=root, mode = 'rb')
    self.oLabel.configure(text=file1.name)    
    rfile1 = file1.read()
    tkMessageBox.showinfo("oy", rfile1, parent=root)

关于python 2.7 Tk更改标签以携带打开文件中的文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13537302/

相关文章:

python - 如何在python中获取旋转线的角度

python - 'MyApp' 没有属性 'label_text' 是什么意思?在哪里添加 label_text?

Python - 将图像转换为一串像素值

python - 从两个文件路径之一加载数据的最干净,最pythonic的方法是什么?为什么我不能捕获两个相同的异常?

python - 如何计算非连续数据中的每周、每月和季节性开始和结束日期

python - matplotlib 饼图中的百分比标签位置

python - 更改 ttk 条目焦点颜色 - Python

python - tkinter 在 MacOS 上始终使窗口保持在顶部

python - Tkinter 和 pyplot 问题中的显示

python - 无法在 tkinter 中显示图像