在Tkinter Python中打开和读取文本文件

时间:2017-09-17 11:47:34

标签: python python-2.7 tkinter pycharm

我试图在Tkinter中创建一个记事本类型的程序,并且无法解决如何将文件的内容显示到标签...

我已经能够将它的内容显示给pyCharm shell但是当我尝试在标签中显示时出现错误。

def openFile():
    fToOpen = filedialog.askopenfilename(filetypes=[("Text files","*.txt")])
    #print(fToOpen.read()) <-- ##This works##
    fileToOpen = open(fToOpen, 'r')
    Label(root, fileToOpen.read()).pack() <-- ##This doesn't##
    fToOpen.close()

我得到的错误是:

Traceback (most recent call last):
  File "C:\Users\Hello\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
  File "C:/Users/Hello/Documents/html/Python/Prog.py", line 143, in openFile
    Label(root, fileToOpen.read()).pack(fill=Y)
  File "C:\Users\Hello\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 2760, in __init__
    Widget.__init__(self, master, 'label', cnf, kw)
  File "C:\Users\Hello\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 2289, in __init__
    classes = [(k, v) for k, v in cnf.items() if isinstance(k, type)]
AttributeError: 'str' object has no attribute 'items'

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

这实际上相当简单。

您需要做的就是打开文件并将信息读入窗口小部件的from tkinter import * root = Tk() with open("file.txt", "r") as f: Label(root, text=f.read()).pack() root.mainloop() 属性。

这可以通过以下方式完成:

SELECT 
    concat(deviceId, cloudtagId) as telemetryid, value as temperature, id, deviceId, 'asd' as 'pk', deviceId as PartitionKey
INTO
    [TableApiCosmosDb]
From
    [devicesMessages]