简体   繁体   English

将文件对话框放入 tk.text

[英]get filedialouge into tk.text

im trying to get text from a loaded file into a ktinker .text, here is the code i have so far, i dont quite understand where a file goes once you have opened it with filedialouge我试图从加载的文件中获取文本到 ktinker .text,这是我到目前为止的代码,一旦你用 filedialouge 打开文件,我不太明白它的去向

from tkinter import *
from tkinter import ttk
from tkinter import filedialog
import tkinter as tk

interface = tk.Tk()
interface.geometry("500x500")
interface.title("Text display")

def openfile():
    return filedialog.askopenfilename()

button = ttk.Button(interface, text="Open text File", command=openfile)  # <------
button.grid(column=1, row=1)

T = tk.Text(interface, height=2, width=30)

T.insert(tk.END, "text file contents here")
T.grid(column=1, row=2)

interface.mainloop()

It's up to you to do something with the return value of askopenfilename .您可以对askopenfilename的返回值做些什么。 Returning it from a button callback is pointless because nothing will see the returned value.从按钮回调中返回它是没有意义的,因为没有人会看到返回的值。

For example, you could save it as a global variable used by some other part of your program:例如,您可以将其保存为程序其他部分使用的全局变量:

def openfile():
    global current_file
    current_file = filedialog.askopenfilename()

Another thing you might do is actually open the file and insert the contents into your text widget:您可能要做的另一件事是实际打开文件并将内容插入到文本小部件中:

def openfile():
    global current_file
    current_file = filedialog.askopenfilename()
    if current_file:
        with open(current_file, "r") as f:
            data = f.read()
            T.insert("end", data)

Though, if you're going to immediately open the file you might want to consider using askopenfile rather than askopenfilename .但是,如果您要立即打开文件,您可能需要考虑使用askopenfile而不是askopenfilename The former opens the file and returns a handle, the later simply returns the filename.前者打开文件并返回一个句柄,后者只返回文件名。

Button can't get value returned from function.按钮无法获取从函数返回的值。 You may have to do all inside openfile - open file, read it and put text in Text您可能必须在openfile执行所有操作 - 打开文件,读取它并将文本放入Text

# from tkinter import * # not preferred
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog

# --- functions ---

def openfile():
    filename = filedialog.askopenfilename()
    if filename:
        data = open(filename).read()
        text.delete('1.0', 'end') # see Bryan Oakley comment why it is better to use string instead of float (but in this situation float 1.0 would work as expected)
        text.insert('end', data)

# --- main ---

interface = tk.Tk()
interface.geometry("500x500")
interface.title("Text display")

button = ttk.Button(interface, text="Open text File", command=openfile)
button.grid(column=1, row=1)

text = tk.Text(interface, height=2, width=30)
text.grid(column=1, row=2)

text.insert('end', "text file contents here")

interface.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM