[Tutor] Getting current listbox item index and bind it to button (Tkinter)

2018-08-07 Thread Ali M
If i delete this line "self.textbox.delete(1.0, tk.END)" in my
enter_meaning function the listbox items won't lower down to 1 item and i
just want 1 item to be shown after user searches the item in entrybox.
what i want to do is: when user searches in entrybox, the listbox items
lowers down to that searched item only, and when i click on that 1
remaining item, the results from db prints in text widget, i want to be
able to also use the button to print it. how can i configure the button for
this? i hope i explained clearly.

import sqlite3 as sqlite
import tkinter as tk
from tkinter import ttk


# GUI Widgets

class EsperantoDict:
def __init__(self, master):

master.title("EsperantoDict")
master.iconbitmap("Esperanto.ico")
master.resizable(False, False)
master.configure(background='#EAFFCD')
self.style = ttk.Style()
self.search_var = tk.StringVar()
self.search_var.trace("w", lambda name, index, mode:
self.update_list())

self.style = ttk.Style()
self.style.configure("TFrame", background='#EAFFCD')
self.style.configure("TButton", background='#C6FF02')
self.style.configure("TLabel", background='#EAFFCD')

self.frame_header = ttk.Frame(master, relief=tk.FLAT)
self.frame_header.config(style="TFrame")
self.frame_header.pack(side=tk.TOP, padx=5, pady=5)

self.logo = tk.PhotoImage(file=r'C:\EsperantoDict\eo.png')
self.small_logo = self.logo.subsample(10, 10)

ttk.Label(self.frame_header, image=self.small_logo).grid(row=0,
column=0, stick="ne", padx=5, pady=5, rowspan=2)
ttk.Label(self.frame_header, text='EsperantoDict', font=('Arial',
18, 'bold')).grid(row=0, column=1)

self.frame_content = ttk.Frame(master)
self.frame_content.config(style="TFrame")
self.frame_content.pack()

self.entry_search = ttk.Entry(self.frame_content,
textvariable=self.search_var, width=30)
self.entry_search.bind('', self.entry_delete)
self.entry_search.bind('', self.entry_insert)
self.entry_search.grid(row=0, column=0, padx=5)
self.entry_search.focus()
self.entry_search.bind("", self.edit_input)

self.button_search = ttk.Button(self.frame_content, text=u"Serĉu")
self.photo_search =
tk.PhotoImage(file=r'C:\EsperantoDict\search.png')
self.small_photo_search = self.photo_search.subsample(3, 3)
self.button_search.config(image=self.small_photo_search,
compound=tk.LEFT, style="TButton")
self.button_search.grid(row=0, column=2, columnspan=1, sticky='nw',
padx=5)
self.button_search.bind('', self.search_word)

self.listbox = tk.Listbox(self.frame_content, height=30, width=30)
self.listbox.grid(row=1, column=0, padx=5)
self.scrollbar = ttk.Scrollbar(self.frame_content,
orient=tk.VERTICAL, command=self.listbox.yview)
self.scrollbar.grid(row=1, column=1, sticky='nsw')
self.listbox.config(yscrollcommand=self.scrollbar.set)
self.listbox.bind('<>', self.enter_meaning)

self.textbox = tk.Text(self.frame_content, relief=tk.GROOVE,
width=60, height=30, borderwidth=2)
self.textbox.config(wrap='word')
self.textbox.grid(row=1, column=2, sticky='w', padx=5)

# SQLite
self.db = sqlite.connect(r'C:\EsperantoDict\test.db')
self.cur = self.db.cursor()
self.cur.execute("SELECT Esperanto FROM Words ORDER BY Esperanto")
for row in self.cur:
self.listbox.insert(tk.END, row)
self.update_list()

def update_list(self):
self.listbox.delete(0, tk.END)
search_term = self.search_var.get().lower()
if search_term == 'type to search':
search_term = ''
self.cur.execute("SELECT Esperanto FROM Words WHERE
LOWER(Esperanto) LIKE ? ORDER BY Esperanto",
 ('%' + search_term + '%',))
for row in self.cur:
item = row[0]
self.listbox.insert(tk.END, item)
for row in range(0, self.listbox.size(), 2):
self.listbox.itemconfigure(row, background="#f0f0ff")

def edit_input(self, tag):
word_to_esp = {'gx': 'ĝ', 'cx': 'ĉ', 'hx': 'ĥ', 'jx': 'ĵ', 'ux':
'ŭ', 'sx': 'ŝ'}
user_input = self.entry_search.get()
user_input = user_input.lower()
for i in word_to_esp:
if user_input.__contains__(i):
a = user_input.replace(i, word_to_esp[i])
return self.search_var.set(a)

# SQLite
def enter_meaning(self, tag):
for index in self.listbox.curselection():
global esperanto
global results
esperanto = self.listbox.get(index)
results = self.cur.execute("SELECT English FROM Words WHERE
Esperanto = ?", (esperanto,))
for row in results:
self.textbox.delete(1.0, tk.END)
self.textbox.insert(tk.END, row[0])

def entry_delete(self, t

Re: [Tutor] Getting current listbox item index and bind it to button (Tkinter)

2018-08-07 Thread Alan Gauld via Tutor
On 06/08/18 20:50, Ali M wrote:
> If i delete this line "self.textbox.delete(1.0, tk.END)" in my
> enter_meaning function the listbox items won't lower down to 1 item and i
> just want 1 item to be shown after user searches the item in entrybox.

So just display 1 item.
What you are currently doing is displaying all the items and then
deleting them except for the last item. Instead, just display
the last item by using an index of -1. It's a lot less work.

> what i want to do is: when user searches in entrybox, the listbox items
> lowers down to that searched item only, 

But what if more than one item is found?
Or can that absolutely never happen? Are you sure?
Does Esperanto not have the concept of synonyms?

> remaining item, the results from db prints in text widget, i want to be
> able to also use the button to print it. how can i configure the button for
> this? 

It should simply be a case of binding the same function to both the
entry and button. You just need to ensure that you create a function
that stands alone to populate the text box. (I'm assuming that when
you say print you really mean "display on screen" and not "print on
paper"?) In other words your enter_meaning method should be assigned
to both events.

Looking at your code you never seem to bind any commands to the
button, therefore it presumably does nothing.


> # SQLite
> def enter_meaning(self, tag):
> for index in self.listbox.curselection():
> global esperanto
> global results
> esperanto = self.listbox.get(index)
> results = self.cur.execute("SELECT English FROM Words WHERE
> Esperanto = ?", (esperanto,))
> for row in results:
> self.textbox.delete(1.0, tk.END)
> self.textbox.insert(tk.END, row[0])

Replace the first for loop with

index = self.listbox.curselection()[-1]
esperanto = self.listbox.get(index)
results = self.cur.execute("SELECT English
FROM Words
WHERE Esperanto = ?", (esperanto,))

And replace the last for loop with

self.textbox.delete(1,0,tk.END)
self.textbox.insert(tk.END, results[-1][0])

It should have the same effect with a lot less processing.
To display the first item use 0 as the index rather
than -1 in the second "loop".

Incidentally, why make esperanto and results global?
You only use them inside this function and they are assigned
new values each time so you may as well make them local.

Also the first loop assumes your user wants you to
search based on the last item selected (if more
than one). Is that correct? Should it perhaps be
the first item? Or all of them?

Or should you configure the listbox so that only one
item at a time can be selected?(ie selectmode=tk.SINGLE)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] How to write a function which reads files

2018-08-07 Thread Rafael Knuth
Hi there,

I got this here:

file_path = "C:\\Users\\...\\MyFile.txt" # path shortened for better readability
with open(file_path) as file_object:
contents = file_object.read()
print(contents)

It works.

Now I want to convert the code above into a function.
This is what I wrote:

def FileReader(file_path):
with open(file_path) as file_object:
contents = file_object.read
return contents

print(FilePrinter("C:\\Users\\...\\MyFile.txt")) # path shortened for
better readability

I got this error message:



How do I fix my function?

Thanks,

Rafael
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to write a function which reads files

2018-08-07 Thread Chris Warrick
On Tue, 7 Aug 2018 at 15:07, Rafael Knuth  wrote:
> def FileReader(file_path):
> with open(file_path) as file_object:
> contents = file_object.read
> return contents
>
> print(FilePrinter("C:\\Users\\...\\MyFile.txt")) # path shortened for
> better readability
>
> I got this error message:
>
> 

You forgot the parentheses (), and are returning a reference to the
function instead of calling it and returning its result. Do this:
contents = file_object.read()

Also, consider using snake_case instead of PascalCase for your
function name, since the latter is typically used for classes, and
perhaps call it read_file to better describe it?

-- 
Chris Warrick 
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to write a function which reads files

2018-08-07 Thread Alan Gauld via Tutor
On 07/08/18 13:46, Rafael Knuth wrote:

> Now I want to convert the code above into a function.
> This is what I wrote:
> 
> def FileReader(file_path):
> with open(file_path) as file_object:
> contents = file_object.read
> return contents
> 
> print(FilePrinter("C:\\Users\\...\\MyFile.txt")) # path shortened for

Note that you used a different name here than in your
function definition!

I'm guessing that's a typo, but its one reason to always
cut 'n paste real code into your emails.

Also as a matter of style its usual in Python to make
function names start with a lower case letter:

def myFunction():

or

def my_function():

But that's just a community convention.

But Chris has answered your original question, you
need to add calling parens.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to write a function which reads files

2018-08-07 Thread Rafael Knuth
> You forgot the parentheses (), and are returning a reference to the
> function instead of calling it and returning its result. Do this:
> contents = file_object.read()

oh, my bad. Thanks!

> Also, consider using snake_case instead of PascalCase for your
> function name, since the latter is typically used for classes, and
> perhaps call it read_file to better describe it?

thanks, I wasn't aware of the naming conventions for functions and classes.
will bear that in mind!

> Note that you used a different name here than in your
> function definition!

another typo. I made that in my original code already.
Thanks, everything works well now!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] python3 - °F/°C printing those degree signs

2018-08-07 Thread Evuraan
Greetings!  How to print °F/°C etc in python3?


(This works on a WSL):

~$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform
>>> platform.release()
'4.4.0-17134-Microsoft'
>>> print('\u00b0'+ " F")
° F

Elsewhere, it no longer seem to work:

 $ python3
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform
>>> platform.release()
'4.4.0-21-generic'
>>> print('\u00b0'+ " F")
Traceback (most recent call last):
  File "", line 1, in 
UnicodeEncodeError: 'ascii' codec can't encode character '\xb0' in
position 0: ordinal not in range(128)


How can we print °F / °C etc. - that should work everywhere on python3
so I can use the same code?

Thanks in advance!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python3 - °F/°C printing those degree signs

2018-08-07 Thread Alan Gauld via Tutor
On 07/08/18 22:32, Evuraan wrote:

 print('\u00b0'+ " F")
> ° F
> 
> Elsewhere, it no longer seem to work:
> 
>  $ python3
> Python 3.5.2 (default, Nov 23 2017, 16:37:01)
> [GCC 5.4.0 20160609] on linux
> Type "help", "copyright", "credits" or "license" for more information.
 import platform
 platform.release()
> '4.4.0-21-generic'
 print('\u00b0'+ " F")
> Traceback (most recent call last):
>   File "", line 1, in 
> UnicodeEncodeError: 'ascii' codec can't encode character '\xb0' in
> position 0: ordinal not in range(128)

To some degree it depends on what you are printing on,
it needs to support unicode. Not all terminals do.

Secondly it needs to be set to unicode for its character
encoding and it appears from the error condition that
yours is set to ascii...

You could try setting

PYTHONIOENCODING="UTF-8"

in your OS shell and see if that helps, but I suspect
there's a better way to deal with it...

PS. You can check the current setting with:

>>> import sys
>>> sys.stdout.encoding

If it says ascii (or anything other than a Unicode setting)
then that's almost certainly your problem.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to write a function which reads files

2018-08-07 Thread Mats Wichmann



Question is already answered, just wanted to add a mini-note.


def FileReader(file_path):with open(file_path) as file_object:
 contents = file_object.readreturn contents
you /can/ return the read method here, which is what this typo does. And
the caller of the function can use it to read, as in:

print(FileReader("...path...")())

that is, since FileReader as originally written returns a callable, you
can call it.

However in this case, since the use of the file context manager (open
using "with" statement) does what it's supposed to, the read will fail,
and you get:

ValueError: I/O operation on closed file.

because as soon as the with statement is exited, things are cleaned up.
That's what context managers do.  That doesn't mean there are not cases
when you will want to return a function/method for use elsewhere, it's
part of the "Python is powerful because functions are first-class"
argument :)


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python3 - °F/°C printing those degree signs

2018-08-07 Thread Steven D'Aprano
On Tue, Aug 07, 2018 at 02:32:58PM -0700, Evuraan wrote:
> Greetings!  How to print °F/°C etc in python3?


In Python 3, you should be able to do:

print('°F/°C')

directly. If you can't, your configuration is broken.

If you are including this is a .py file, make sure your text editor is 
set to use UTF-8 as the encoding.


> (This works on a WSL):

WSL?


> ~$ python3
> Python 3.5.2 (default, Nov 17 2016, 17:05:23)
> [GCC 5.4.0 20160609] on linux
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import platform
> >>> platform.release()
> '4.4.0-17134-Microsoft'

Microsoft Linux?


> >>> print('\u00b0'+ " F")
> ° F


You don't need to use escape codes for this, but if you do, try this:

print('\u00b0 F')

 
> Elsewhere, it no longer seem to work:
> 
>  $ python3
> Python 3.5.2 (default, Nov 23 2017, 16:37:01)
> [GCC 5.4.0 20160609] on linux
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import platform
> >>> platform.release()
> '4.4.0-21-generic'

What is this? OS X (Macinintosh), Windows, Windows with cgwin, Linux, 
some other Unix?

What does os.name return?


> >>> print('\u00b0'+ " F")
> Traceback (most recent call last):
>   File "", line 1, in 
> UnicodeEncodeError: 'ascii' codec can't encode character '\xb0' in
> position 0: ordinal not in range(128)

Until now, I would have said that error is literally impossible in 
Python 3.5.

Unless you have made a copy-and-paste error, and aren't showing us the 
correct output, I can't imagine how you are getting that error. This is 
very weird.

Hmmm... thinking... what do these return?

sys.getdefaultencoding()

sys.stdout.encoding



-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python3 - °F/°C printing those degree signs

2018-08-07 Thread Evuraan
>
> You could try setting
>
> PYTHONIOENCODING="UTF-8"
>
> in your OS shell and see if that helps, but I suspect
> there's a better way to deal with it...
>

Thank you! That was it!

Exporting thusly made it behave:

$ export PYTHONIOENCODING="UTF-8"
$ python3
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print('\u00b0'+ "F")
°F
>>>

I've come across this env variable even before, but overlooked it this
time again. Much appreciated!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor