Python file I/O with Tkinter - python

I'm trying to open a .txt file with Python. I'm trying to fill a Tkinter text widget with the files contents.
However with the following snippet, when I try to open the files contents and put it in a the text widget self.Te, nothing happens. Any clues?
Snippet:
self.Open = tkFileDialog.askopenfilename(initialdir='C:')
text_file = open(self.Open, "r")
# self.Te is a text widget
self.Te.insert('1.0', text_file.read())

Here is a working example:
#!/usr/bin/env python
from Tkinter import *
from tkFileDialog import askopenfilename
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.button = Button(frame, text="QUIT", command=frame.quit)
self.button.pack(side=BOTTOM)
self.text = Text(frame)
self.text.pack(side=TOP)
self.choosen = askopenfilename(initialdir='~')
self.text.insert(END, open(self.choosen).read())
root = Tk()
app = App(root)
root.mainloop()
See also Text widget method documentation:
http://www.pythonware.com/library/tkinter/introduction/x8369-methods.htm
... Insert text at the given position (typically INSERT or END) ...

Related

Picture won't open in File Dialog, Tkinter, Pillow

I have written this.
Its short and supposed to open a file dialog window, with buttons "open a file, turn, save, exit."
I want to open a jpeg, turn it 180° and then save it and quit.
The program starts, but doesnt open the picture in the file dialog window after I select it in the browser.
from tkinter import *
from PIL import Image, ImageTk
from tkinter import ttk
from tkinter import filedialog
from tkinter.filedialog import askopenfilenames
root = Tk() ##pro Tkinter
root.title('Image Browser')
root.geometry('100x100')
def open():
global my_image
root.filename = filedialog.askopenfilenames(initialdir='/gui/pillow', filetypes=[('Images','*.jpg *.jpeg *.png')])
#my_label = Label(root, text = root.filename).pack()
my_image = ImageTk.PhotoImage(Image.open(root.filename))
my_image_label = Label(image=my_image).pack()
def turn():
return
my_image = my_image.transpose(Image.FLIP_RIGHT_LEFT)
def save():
return
my_image.save('somepic.jpg')
button = Button (root, text = 'Select a File', command = open)
button.pack()
button4 = Button (root, text = 'Turn', command = turn)
button4.pack()
button2 = Button (root, text = 'Save', command = save)
button2.pack()
button3 = Button(root, text = 'Exit', command = jadro.quit)
button3.pack()
root.mainloop()
After I select and try to open the file, it says this
AttributeError: 'tuple' object has no attribute 'seek'
I feel like I've tried everything, but cant seem to solve it.
Thanks for any help
askopenfilenames return a tuple.
Try this instead
my_image = ImageTk.PhotoImage(Image.open(root.filename[0]))
From Python DOC
tkinter.filedialog.askopenfilename(**options)
tkinter.filedialog.askopenfilenames(**options)
The above two functions create an Open dialog and return the selected filename(s) that correspond to existing file(s).
Therefore askopenfilenames() returns a tuple of filenames, instead Image.open(fp) requires a file pointer as argument, not a tuple.
From Pillow DOC:
PIL.Image.open(fp, mode='r', formats=None)
fp – A filename (string), pathlib.Path object or a file object. The file object must implement file.read, file.seek, and file.tell methods, and be opened in binary mode.

How to get a user-selected file and feed it to a python program in Tkinter

I am currently messing about with Tkinter creating an interface for a project I created. The program takes in a bunch of file paths as inputs for it to run. I'm trying to create a tkinter interface where I can upload the 4 files I need or at least somehow get the filepaths and the. feed those to the program. Here is what I have:
import sys
import os
import comparatorclass
from tkinter import *
from tkinter.ttk import *
from tkinter.filedialog import askopenfile
root=Tk()
root.geometry('1000x1000')
def open_file():
file = askopenfile(mode ='r', filetypes =[('Python Files', '*.py')])
if file is not None:
content = file.read()
print(content)
def run_comparator():
comparatorclass.main()
button2 = Button(root, text ='Open', command = lambda:open_file())
button2.pack(side = TOP, pady = 10)
button1 = Button(root,text="hello",command= run_comparator)
button1.pack()
root.mainloop()
as you can see, I have two buttons. The issue I'm having is how to connect my openfile function to my run_comparator function such that the 4 files I need to open are passed on to the run_comparator

Not able to use tkinter in ArcMap

I am using Tkinter in ArcMap Add-in python code. Tkinter UI is opening well but then it closes or crashes ArcMap.
I am using the below code.
import arcpy
import pythonaddins
from Tkinter import *
import tkMessageBox
class ButtonClass1(object):
"""Implementation for Testing_addin.button (Button)"""
def __init__(self):
self.enabled = True
self.checked = False
def onClick(self):
root = Tk()
lbl = Label(root, text = "Hello")
lbl.pack()
btn = Button(root, text = "OK")
root.mainloop()
pass
Thank you!

How to get the text out of a scrolledtext widget?

I am new to the tkinter python module. I try to do a project. I learned something new about the menus and I'm trying to make a little UI project that allows the user to write something in a scrolled text widget and then save it (using the sys module).
I've already tried some things that worked at buttons. For example .get() but it didn't work. I also tried the ["text"] method.
import tkinter, sys
root = tkinter.Tk()
class saveProject:
def __init__(self, master):
self.master = master
self.textFrame = tkinter.scrolledtext.ScrolledText(self.master, width=100, bd=10, relief="raised")
self.textFrame.pack()
def save(self):
#self.saveText = self.textFrame.get()
self.saveText = self.textFrame["text"]
project = saveProject(root)
root.mainloop()
The problem is, as I already said, I don't know how to get the text out of a tkinter.scrolledtext.ScrolledText widget.
So, out of curiosity I tried what described here (same link in my comment to the OP question). It works also for the scrolledtext.
import tkinter, sys
from tkinter import scrolledtext
root = tkinter.Tk()
class saveProject:
def __init__(self, master):
self.master = master
self.textFrame = scrolledtext.ScrolledText(self.master, width=100, bd=10, relief="raised")
self.textFrame.pack()
self.saveb = tkinter.Button(self.master, text="Save", command= lambda : self.save())
self.saveb.pack()
def save(self):
cur_inp = self.textFrame.get("1.0", tkinter.END)
fl = open("output.txt", "w")
fl.write(cur_inp)
project = saveProject(root)
root.mainloop()
I've added a save button at the bottom of the ScrolledText widget. The widget content is saved inside the output.txt area.
help(ScrolledText) indicates it's a subclass of the tkinter.Text widget, which apparently means that the way to get the text from it is the same — via its get() method using "Text widget indices" (here's some documentation about them).
Below is an example that gets all of the text in the widget (I added a Save text Button to test the save() method):
import sys
import tkinter as tk
from tkinter.scrolledtext import ScrolledText
class SaveProject:
def __init__(self, master):
self.master = master
self.textFrame = ScrolledText(self.master, width=100, bd=10, relief="raised")
self.textFrame.pack()
# Added for testing.
self.save_btn = tk.Button(self.master, text='Save text', command=self.save)
self.save_btn.pack()
def save(self):
self.saveText = self.textFrame.get('1.0', tk.END) # Get all text in widget.
print('self.saveText:', self.saveText)
root = tk.Tk()
project = SaveProject(root)
root.mainloop()

<Command-a> for Text - Tkinter

I found the below code :
def callback(ev):
ev.widget.select_range(0, 'end')
root = Tk()
t = Text(root, height=10, width=40)
t.pack()
t.bind('<Command-a>', callback) //WORKS for ENTRY
root.mainloop()
I'm basically trying to make cmd + a or Ctrl + a (Windows) work for Text in Tkinter.
Error (When I give the command : cmd-a in text):
'Text' object has no attribute 'select_range'
The code is ok except that you are inventing methods on the Text widget. However, if you look at the bindings on the widget class (Text) there are some virtual events defined
>>> '<<SelectAll>>' in root.bind_class('Text')
True
So in your handler for the keyboard event, use event_generate to raise a SelectAll virtual event.
import tkinter as tk
def select_all(ev):
ev.widget.event_generate('<<SelectAll>>')
root = tk.Tk()
txt = tk.Text(root)
txt.pack()
txt.bind('<Control-A>', select_all)
Text class does not have select_range() function, that is why you got that error message. But you can use bind_class() to bind events to the Text class widgets. Here is a dirty demo:
import tkinter as tk
def simulate_contral_a(e):
e.widget.tag_add("sel","1.0","end")
root = tk.Tk()
root.bind_class("Text","<Control-a>", simulate_contral_a)
T = tk.Text(root, height=2, width=30)
T.pack()
T.insert(tk.END, "Press Ctrl+a\nto select me\n")
root.mainloop()
Run this MCVE above and press Ctrl + a to see its effect:

Categories

Resources