Choosing a file in Python3 - python

Where is the tkFileDialog module in Python 3? The question Choosing a file in Python with simple Dialog references the module using:
from Tkinter import Tk
from tkFileDialog import askopenfilename
but using that (after changing Tkinter to tkinter) in Python 3 gets:
Traceback (most recent call last):
File "C:\Documents and Settings\me\My Documents\file.pyw", line 5, in <module>
import tkFileDialog
ImportError: No module named tkFileDialog
The python 2.7.2 doc (docs.python.org) says:
tkFileDialog
Common dialogs to allow the user to specify a file to open or save.
These have been renamed as well in Python 3.0; they were all made submodules of the new tkinter package.
but it gives no hint what the new names would be, and searching for tkFileDialog and askopenfilename in the 3.2.2 docs returns nothing at all (not even a mapping from the old names to the new submodule names.)
Trying the obvious doesn't do jack:
from tkinter import askopenfilename, asksaveasfilename
ImportError: cannot import name askopenfilename
How do you call the equivalent of askopenfilename() in Python 3?

You're looking for tkinter.filedialog as noted in the docs.
from tkinter import filedialog
You can look at what methods/classes are in filedialog by running help(filedialog) in the python interpreter. I think filedialog.LoadFileDialog is what you're looking for.

You can try something like this:
from tkinter import *
root = Tk()
root.filename = filedialog.askopenfilename(initialdir = "E:/Images",title = "choose your file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
print (root.filename)
root.withdraw()

Related

How to properly import tcl file

I am trying to use the Azure theme in a tkinter application i made. I used the code from github to import the theme(https://github.com/rdbende/Azure-ttk-theme). I put the "azure.tcl" file in the folder with the python file and got the error "_tkinter.TclError: couldn't read file "./theme/light.tcl": no such file or directory". I then tried making a simpler tkinter program with the same ttk theme import code from before but this time in it's own folder with the tcl file. I still got the same error message. When i download the file from github, i ran the example python file and worked just fine.
Here is the code i use to import the file.
import tkinter as tk
from tkinter import Label, ttk
root = tk.Tk()
root.tk.call("source", "azure.tcl")
root.tk.call("set_theme", "dark")
root.geometry("300x300")
L1 = Label(root, text="Hello world")
L1.grid(row=1, column=1)
root.mainloop()
If you do not have this "TKinterModernThemes" library, then you should also install it with below code:
pip install TKinterModernThemes
Then, you can keep your script as it is but just a few arrangements.
Importing Library:
import TKinterModernThemes as TKMT
Threat like window.root is your tk.Tk() object:
import tkinter as tk
from tkinter import Label, ttk
import TKinterModernThemes as TKMT
window = TKMT.ThemedTKinterFrame("%yourProjectName","azure","dark")
window.root.geometry("300x300")
L1 = Label(window.root, text="Hello world")
L1.grid(row=1, column=1)
window.root.mainloop()

Why does child have to import same modules parent did?

My main Python program (script to most) has elaborate import statements I'd rather not repeat in modules I import:
from __future__ import print_function # Must be first import
from __future__ import with_statement # Error handling for file opens
try:
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.font as font
import tkinter.filedialog as filedialog
import tkinter.messagebox as messagebox
PYTHON_VER="3"
except ImportError: # Python 2
import Tkinter as tk
import ttk
import tkFont as font
import tkFileDialog as filedialog
import tkMessageBox as messagebox
PYTHON_VER="2"
# print ("Python version: ", PYTHON_VER)
import subprocess32 as sp
import sys
import os
import time
import datetime
from PIL import Image, ImageTk, ImageDraw, ImageFont
import pickle
from random import shuffle
import getpass # Get user name for file storage
import locale # To set thousands separator as , or .
locale.setlocale(locale.LC_ALL, '') # Use '' for auto
# mserve modules
import location as lc # Home grown module
As my program/script approaches 5,000 lines I've come over to the light side / (Dark side?) and started using imported modules of my own design. The first module is called location.py but!, lo and behold I've had to repeat import statements already imported in the parent program mserve.
EG at header:
from __future__ import print_function # Must be first import
import getpass
import os
import pickle
import time
And just tonight on a new function I'm writing:
import Tkinter as tk
class MsgDisplay:
''' Text Widget with status messages
'''
def __init__(self, title, toplevel, width, height):
self.line_cnt = 0 # Message lines displayed so far
toplevel.update_idletasks() # Get up-to-date window co-ords
x = toplevel.winfo_x()
y = toplevel.winfo_y()
w = toplevel.winfo_width()
h = toplevel.winfo_height()
xd = (w/2) - (width/2)
yd = (h/2) - (height/2)
print('x:',x,'y:',y,'w:',w,'h:',h,
'width:',width,'height:',height,'xd:',xd,'yd:',yd)
''' Mount message textbox window at centered in passed toplevel '''
self.msg_top = tk.Toplevel()
self.textbox = tk.Text(self.msg_top, height=height, width=width)
self.msg_top.geometry('%dx%d+%d+%d'%(width, height, x + xd, y + yd))
# self.textbox.columnconfigure(0, weight=1)
# self.textbox.rowconfigure(0, weight=1)
self.textbox.pack()
self.textbox.insert(tk.END, "Just a text Widget\nin two lines\n")
def Update(self, msg_list):
self.textbox.insert(tk.END, "Just a text Widget\nin two lines\n")
time.sleep(.1)
def Close(self):
self.msg_top.destroy()
The new import I just added:
import Tkinter as tk
Is a shortcut / fudge because production version would need to be:
try:
import tkinter as tk
except ImportError: # Python 2
import Tkinter as tk
Before preaching python 2.7.12 is obsolete please note I'm using Ubuntu 16.04 whose EOL is 2021. Also note we use Windows 2008 Server at work and legacy systems written in COBOL are common so who cares?
I must be doing something wrong because a module that is imported should not have to import what parent already did? In a normal environment the child should know / inherent what the parent already knows.
As an aside, tonight's new class "MsgDisplay" should be in parent and not in child. It was simpler to put the class in the child rather than figuring out how a child could call a parent class.
I must be doing something wrong because a module that is imported should not have > to import what parent already did? In a normal environment the child should know > inherent what the parent already knows.
You are describing a cpp-like include system where declarations are just placed in order in a single translation unit. That doesn't apply to python. Importing the same module everywhere you use it is necessary. Think about importing as binding the modules contents to the local namespace. If you use module A contents in module B you need to import it in B even if module C already imports A and later B. Don't worry too much about performance. Once a module is loaded by python interpreter remaining imports are not very expensive.

Python: import not importing messagebox

from tkinter import *
from tkinter import messagebox
root = Tk()
messagebox.showinfo("Hello world", "you are the best")
root.mainloop()
Why do I have to have to import messagebox explicitly when I am import all using *
messagebox is a submodule of the tkinter package.
The wildcard import syntax doesn't import submodules, only the names that are defined in the tkinter package itself.
Therefore you need to import the messagebox submodule explicitly.
References
https://docs.python.org/3/library/tkinter.html#tkinter-modules
https://docs.python.org/3/reference/simple_stmts.html#the-import-statement
Relevant tkinter sources
https://github.com/python/cpython/blob/3.6/Lib/tkinter/__init__.py
https://github.com/python/cpython/blob/3.6/Lib/tkinter/messagebox.py

Tkinter not working in cmd (working in IDLE)

I am trying to display a directory selection dialog box (for getting a path and then for saving downloaded stuff).The code runs fine in IDLE but when i try to run it in CMD i get this error
NameError: name 'Tk' is not defined
I am using tkinter for gui.
Code Snippet
from tkinter import filedialog
root = Tk()
root.withdraw()
filename = filedialog.askdirectory()
Using Python 3.4.3. Any help/suggestions?
The statement from tkinter import filedialog only imports the filedialog module from tkinter. If you want the usual Tkinter stuff, you have to import that too. I'd recommend import tkinter as tk and then referring to it with e.g. root = tk.Tk() so you don't just dump everything into the global namespace. Or, if you really just want the root object, use from tkinter import Tk.
from tkinter import Tk
from tkinter import filedialog
root = Tk()
root.withdraw()
filename = filedialog.askdirectory()

tk messagebox import confusion

I'm just beginning to learn tkinter at the moment, and when importing messagebox I found that I must not really understand import statements.
The thing that confuses me is that:
import tkinter as tk
def text_box():
if tk.messagebox.askokcancel("Quit", "Never Mind"):
root.destroy()
root = tk.Tk()
button = tk.Button(root, text="Press the button", command=text_box)
button.pack()
root.mainloop()
compiles fine, but pressing the button gives the error 'module' object has no attribute 'messagebox', while the code:
import tkinter as tk
from tkinter import messagebox
...
if messagebox.askokcancel("Quit", "Never Mind"):
...
...works without a hitch.
I get a similar error if I import with from tkinter import *.
The help for tkinter shows messagebox in the list of PACKAGE CONTENTS, but I just can't load it in the normal way.
So my question is, why...and what is it about importing that I don't understand?
Just thought I should mention—the code only works in Python 3, and in Python 2.x messagebox is called tkMessageBox and is not defined in tkinter.
tkinter.messagebox is a module, not a class.
As it isn't imported in tkinter.__init__.py, you explicitly have to import it before you can use it.
import tkinter
tkinter.messagebox # would raise an ImportError
from tkinter import messagebox
tkinter.messagebox # now it's available eiter as `messagebox` or `tkinter.messagebox`
try this
import sys
from tkinter import *
... and your code

Categories

Resources