Better looking Tkinter File Dialogs for Python 2.7 - python-2.7

In my application, the user needs to browse for files. However, the askdirectory from tkFileDialog isn't really comfortable for using and browsing files since it's somewhat outdated.
It looks like this:
What I want to achieve should look like the "default" windows browse dialog. Like this:
(Source https://www.pythontutorial.net/tkinter/tkinter-open-file-dialog/)
I am not sure (since I couldn't find proof) but I remember someone telling me that it looks like this because I am using Python 2.7 and not 3+.
Is that true? Does an alternative exist?

It seems it has something to do with your version, as I have done a bit of research and I am using python 3 with the included tkinter and it shows a normal windows explorer popup. So, if you are using one of the up-to-date versions, it should be the OS' default. (I am unable to test that as python 2 will not work properly on my machine although I can confirm since you are using an older one)
I recreated your case with this code:
from tkinter import *
root = Tk()
filedialog.askdirectory()
root.mainloop()

You can try using askopenfilename(). It displays the standard Open File dialog box.
For example:
from tkinter import *
from tkinter import filedialog as fd
root = Tk()
root.title("Button to open files")
root.geometry("500x500")
def openfd(*args):
askk = askopenfilename()
btn = Button(root, text="Click to open file", command=openfd)
btn.place(x=200, y=200)
root.mainloop()
You can read more about it at https://www.pythontutorial.net/tkinter/tkinter-open-file-dialog/.

Related

Python | Tkinter | TkCalendar : how to customize 'DateEntry Date Picker' object? like increasing Width, and more?

I'm developing a simple Python stand-alone application, that uses a GUI datePicker, and I went for using 'from tkcalendar import DateEntry'. | using python 2.7 (for older windows PC)
while using 'DateEntry - Date Picker', I not able to find a few major things, even the documentation doesn't explain on this. I went through these:
https://tkcalendar.readthedocs.io/en/stable/DateEntry.html#
https://tkdocs.com/shipman/
https://www.plus2net.com/python/tkinter-DateEntry.php
I'm looking ways to
Change width of Widget
open widget on click of entry/input bar (not only drop-down arrow)
Code Ex:
DateEntry(window, date_pattern='yyyy-MM-dd', width= 67, background=CONST.TITLE_BG_COLOR, bad=2)
Any suggestion, references and even alternative are appreciated. Thanks.

Cannot insert a image in Tkinter Label even after anchoring it

Code Here is my code
I've attached a link of well formatted code image and file
import os.
from Tkinter import *.
root=Tk().
m=Label(root,text="Processing...",fg="bue",font="calibri 35 bold").
os.chdir("f:\\").
im=PhotoImage("MM.jpg")
ok=Toplevel(root)
s=Label(root,text="Img",image=im)
s.photo=im
s.image=im
s.grid(row=0,column=0) m.grid(row=1,column=0)
but=None.
def dat():.    
global s,root,but.    
s.destroy().    
m.destroy().
but=Label(root,text="Done").  
but.pack().
  root.overrideredirect(False).
root.mainloop().
I've attached a image of properly indented code in the link
or my file's drive link
Drive link
Please reformat your code so that you can get better help and quickly.
Meanwhile I have a code below showing you how to properly open a .jpg file and have it appear in a tk.Label. I hope this basics can guide you to solve your code problem.
from Tkinter import *
from PIL import Image, ImageTk #added
root=Tk()
filename = "minion.jpg" # Put your filename (can also use full path)here
im = Image.open(filename) #added
im=ImageTk.PhotoImage(im) #revised
s=Label(root,text="Img",image=im)
s.grid(row=0,column=0)
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)
root.mainloop()
Update:
I have added the image commands into your script. Do note, your code contained several wrong indents, which pycharm highlighted to me. There were typos, wrong placement of certain commands and missing import statement. I took the liberty to correct them sufficient enough for tkinter to generate a tk window with your label and image, so to be able to answer your question. A screen shot of pycharm with python2.7, a revised code and tk window with label and image is attached below.
Note: For .jpg image you need the PIL or Pillow modules installed to open such file type. Do make sure you have that. If you don't have, follow the instructions in this webpage to install it. That is the limitation of the PIL.ImageTk.PhotoImage method. You can read more from this website.

Auto-save function implementation with Python and Tkinter

This might be a general question. I'm modifying a Python code wrote by former colleague. The main purpose of the code is
Read some file from local
Pop out a GUI to do some modification
Save the file to local
The GUI is wrote with Python and Tkinter. I'm not very familiar with Tkinter actually. Right now, I want to implement an auto-save function, which runs alongside Tkinter's mainloop(), and save modified files automatically for every 5 minutes. I think I will need a second thread to do this. But I'm not sure how. Any ideas or examples will be much appreciated!! Thanks
Just like the comment says, use 'after' recursion.
import Tkinter
root = Tkinter.Tk()
def autosave():
# do something you want
root.after(60000 * 5, autosave) # time in milliseconds
autosave()
root.mainloop()
Threaded solution is possible too:
import threading
import time
import Tkinter
root = Tkinter.Tk()
def autosave():
while True:
# do something you want
time.sleep(60 * 5)
saver = threading.Thread(target=autosave)
saver.start()
root.mainloop()
before leaving I use sys.exit() to kill all running threads and gui. Not sure is it proper way to do it or not.

tkinter button to open new window and run script

I have a tkinter button that I want to use to run an existing python script in a new cmd window. How would I do that?
I can get the new cmd window to appear, but how do I run the script in it?
Thanks,
Chris.
Multiline code is more readable if you edit your question to add it (allowed, just mark it as edited and say so in the comment) rather than in a comment.
from Tkinter import *
from sys import executable
from subprocess import Popen, CREATE_NEW_CONSOLE
import os
def delprof(): Popen(["cmd.exe"], creationflags=CREATE_NEW_CONSOLE) `
If you get a console with a prompt, you can run python or do anything else. To run a particular python program, the following works for me (3.4).
from tkinter import *
from subprocess import call
pyprog = 'tem2.py'
def callpy(): call(['python', '-i', pyprog] )
root = Tk()
Button(root, text='Run', command=callpy).pack()
root.mainloop()
When running a program, the console normally disappears when the program ends. To prevent that with a python program, so output can be seen, either put something like
input('hit enter to exit')
at the end of the program or start it with '-i', as I did above. This also allows execution of additional interactive statements to examine the result

Disable or Catch VTK warnings in vtkOutputWindow when embedding Mayavi

I'd like to either disable the VTK warning window or, better yet, catch them to handle with my application's logging system. My application is using an embedded mayavi view, and I don't want error windows popping up that I have no control over. The following code demonstrates the warning window.
import numpy as np
from mayavi import mlab
x1 = np.array([1, 1, 2, 3])
y1 = np.array([1, 1, 4, 2])
z1 = np.array([1, 1, 5, 1])
mlab.plot3d(x1, y1, z1)
mlab.show()
Ok, I've done some research and discovered that vtk.vtkObject.GlobalWarningDisplayOff() will disable the window completely, which is nice. Better yet the followingcode will log the warnings to a file (found it here):
def redirect_vtk_messages ():
""" Can be used to redirect VTK related error messages to a
file."""
import tempfile
tempfile.template = 'vtk-err'
f = tempfile.mktemp('.log')
log = vtkpython.vtkFileOutputWindow()
log.SetFlush(1)
log.SetFileName(f)
log.SetInstance(log)
So while this is nice, I'm still unable to pipe the warnings directly into a logging handler. I'd rather not have to have a vtk_log file next to my regular log files. Also I might want to handle the warnings in my GUI somehow, or give the user options on how to handle them and constantly watching a log file for changes seems like a poor way to do that.
Any suggestions on a robust pythonic way to handle vtk warnings in an application which embeds mayavi/vtk?
I don't know whether this will work in the Mayavi environment, but this works for Python wrappings to VTK
# pipe vtk output errors to file
errOut = vtk.vtkFileOutputWindow()
errOut.SetFileName("VTK Error Out.txt")
vtkStdErrOut = vtk.vtkOutputWindow()
vtkStdErrOut.SetInstance(errOut)
I guess this partially answer your question, but you could implement an error observer in python as explained here http://public.kitware.com/pipermail/vtkusers/2012-June/074703.html and add it to the vtk class you are interested.
In c++ I find much simpler to redirect the output to stderr (this example is for windows):
vtkSmartPointer<vtkWin32OutputWindow> myOutputWindow = vtkSmartPointer<vtkWin32OutputWindow>::New();
myOutputWindow->SetSendToStdErr(true);
vtkOutputWindow::SetInstance(myOutputWindow);
In python I tried
ow = vtk.vtkOutputWindow()
ow.SendToStdErrOn()
it sends the error to console, but I still see the vtk window and it doesn't really seem catching the errors.
Another option could be to recompile vtk with VTK_USE_DISPLAY turned off ( http://osdir.com/ml/python-enthought-devel/2009-11/msg00164.html). I am not going to try this because I am using the vtk distribution already compiled in paraview
You can create a subclass deriving from vtkOutputWindow and implement your message handling in the method void DisplayText(const char* someText). I did this is in a C++ project to redirect all output to cerr and even suppress specific warnings.
An approach I found similar to #SciCompLover's answer that suppresses the output window while also printing to the console:
import vtk
vtk_out = vtk.vtkOutputWindow()
vtk_out.SetInstance(vtk_out)
Tested on Mayavi 4.7.1 with VTK 8.2.0 on Windows and MacOS.