0

I'm trying to make my way through the documenation, but I'm having a hard time trying to find three specific things.

  1. What is a text input.
  2. How to get the text in a text input.
  3. How to set the text on a text input.

Basically I would like to do as I just did in this example for javascript (it's really simple):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>SmallForm</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
    <script>var db = openDatabase('mydb', '1.0', 'temporal database', 2 * 1024 * 1024);
    db.transaction(function (tx) {
        tx.executeSql('CREATE TABLE foo (id unique, field1 text, field2 text)');
    });
    saveData = function(){
        db.transaction(function (tx) {
            var id = $('input[name=id]').val();
            var field1 = $('input[name=field1]').val();
            var field2 = $('input[name=field2]').val();
            tx.executeSql('insert or replace into foo values (?, ?, ?)', [id , field1, field2]);
        });
    };
    loadData = function(){
        db.transaction(function (tx) {
            var id = $('input[name=id]').val();
            tx.executeSql('select * from foo where id =?', [id],function (tx, results) {
                var len = results.rows.length;
                if (len != 1){
                    var text = len > 1? "bad data" : "no data";
                    $('input[name=field1]').val(text);
                    $('input[name=field2]').val(text);
                }
                else {
                    $('input[name=field1]').val(results.rows.item(0).field1);
                    $('input[name=field2]').val(results.rows.item(0).field2);
                }
            });
        });
    };
    </script>
</head>
<body>
    <div class="line">ID:<input type="text" name="id" value="Introduce the ID first"><input type="button" onclick="loadData()" value="Load"></div>
    <div class="line">Field1:<input type="text" name="field1" value="some field"></div>
    <div class="line">Field2:<input type="text" name="field2" value="another field"></div>
    <div class="line"><input type="button" onclick="saveData()" value="Save"></div>
</body>
</html>

I could not find this documentation for Python and I don't understand how the Tcl/Tk documentation maps to Python code. I guess I should check these:

But I understand nothing, either that is complex, I'm stupid or I skipped some important bits of information. Most probably it's a combination of all the former.

Thank you. Sorry if I did something wrong. All replies and feedback are welcome.

PD: I've been working on the code from @mmgp and I've produced this:

import sqlite3, tkinter as tk

def save_data():
  insertQuery = 'insert or replace into allData values(%s)'%(','.join(map(lambda x:'?',fields)))
  cursor.execute(insertQuery, tuple(map(lambda x: variables[x].get(), fields)))
  db.commit()

def load_data():
  cursor.execute('select * from allData where %s = ?'%fields[0], [variables[fields[0]].get()])
  row = cursor.fetchone()
  if row is None:
    for f in fields:
      variables[f].set("Bad data request")
    return
  for i in range(len(fields)):
    variables[fields[i]].set(row[i])


root = tk.Tk()
root.title('Fielder2013')
fields = ['id', 'field1', 'field2']
variables = {}
buttons = {'Load':load_data, 'Save':save_data}
dfields = {}

for i in range(len(fields)):
  e = fields[i]
  dfields[e] = (tk.Label(text=e), tk.Entry())
  dfields[e][0].grid(row=i, column=0)
  dfields[e][1].grid(row=i, column=1)
  variables[e] = tk.StringVar()
  dfields[e][1]["textvariable"] = variables[e]
i = 0
for e in buttons:
  c = buttons[e]
  buttons[e] = tk.Button(text=e)
  buttons[e]['command'] = c
  buttons[e].grid(row = i, column=2)
  i+=1

with sqlite3.connect('database.sqlite3') as db:
  cursor = db.cursor()
  cursor.execute('create table if not exists allData (%s text unique%s)'%(
                 fields[0], ''.join(map(lambda e: ', %s text'%e, fields[1:]))))
  root.mainloop()
  db.commit()

The code may not be the clearest code you have ever seen but my little brain was trying to grasp some new concepts. I think it may be helpful for someone though.

1 Answer 1

3

The official documentation can always be found at http://docs.python.org/2/library/tkinter.html. Also, searching for terms like "python tkinter" will return a lot of other places with useful documentation.

Following is an example that does nearly nothing, but replicates your code without calling into some database.

import Tkinter

def save_data(form):
    for widget in form:
        print widget.get()

def load_data(id_value, form):
    for i, widget in enumerate(form):
        widget.delete(0, 'end')
        widget.insert(0, id_value * (i + 2))

root = Tkinter.Tk()

lbl_id = Tkinter.Label(text=u'ID')
entry_id = Tkinter.Entry()
entry_load = Tkinter.Button(text=u'Load')
lbl_field1 = Tkinter.Label(text=u'Field 1')
entry_field1 = Tkinter.Entry()
entry_save = Tkinter.Button(text=u'Save')

lbl_id.grid(row=0, column=0)
entry_id.grid(row=0, column=1)
entry_load.grid(row=0, column=2)
lbl_field1.grid(row=1, column=0)
entry_field1.grid(row=1, column=1)
entry_save.grid(row=2, column=2)

form = [entry_field1]
entry_load['command'] = lambda: load_data(entry_id.get(), form)
entry_save['command'] = lambda: save_data(form)

root.mainloop()
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer. I think that's exactly what I needed to get through the initial steps in the learning curve, now everything makes sense, or at least many things. I've worked on your code and made a new version that I'm adding now to the initial post. Thank you again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.