0

I'm fairly new to programming and basically I have no idea what I'm doing.

I'm trying to make a write simple UI that that can take an input and write it to a mongodb.

import pymongo
from tkinter import *
from tkinter import ttk

class Input:

    def __init__(self, root,):

        self.myclient = pymongo.MongoClient("mongodb://localhost:27017/")

        self.mydb = self.myclient["mydatabase"]

        self.mycol = self.mydb["input"]

        title_label = Label(root, text="input")

        title_label.grid(row=0, column=0, padx=10, pady=10, sticky=W)

        self.input_value = StringVar(root, value="")

        self.input = ttk.Entry(root, textvariable=self.input_value)

        self.input.grid(row=0, column=1, padx=10, pady=10, sticky=W)

        self.submit_button = ttk.Button(root,
                                        text="Submit",
                                        command=self.submit())
        self.submit_button.grid(row=1, column=0,
                                padx=10, pady=10, sticky=W)

    def submit(self):
        entry = {"input": self.input_value}
        self.mycol.insert(entry)


root = Tk()

In = Input(root)

root.mainloop()

When trying to run this I get

bson.errors.InvalidDocument: Cannot encode object: <tkinter.StringVar object at 0x000001EC62343908>

I tried converting input_value to 'normal' string

self.input_value = str(StringVar(root, value=""))

By doing that I get the program to run but whatever I input into the entry field it writes 'PY_VAR0' to the database.

What am I doing wrong?

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
DracoTomes
  • 21
  • 3
  • Other way around. Rather than "assign a simple string" you need to coerce `self.input_value` to a "simple string", or at least a valid type for the BSON serializer. So `{ "input": str(self.input_value) }` – Neil Lunn Mar 25 '19 at 07:45
  • Doing that still results in "PY_VAR0" being written to the database. – DracoTomes Mar 25 '19 at 07:52
  • 1
    [Get contents of a Tkinter Entry widget](https://stackoverflow.com/questions/9815063/get-contents-of-a-tkinter-entry-widget) then? Possibly returns a dict from which you might need to further extract specific fields. – Neil Lunn Mar 25 '19 at 08:00

1 Answers1

1

Thanks Neil Lunn.

entry = {"input": self.input_value.get()}

is now working using the get method.

Another problem I found is that I wrote

self.submit_button = ttk.Button(root,
                                text="Submit",
                                command=self.submit())

It actually needs to be

self.submit_button = ttk.Button(root,
                                text="Submit",
                                command=self.submit)

Without the parenthesis on self.submit. Those caused the funktion to be executed at the start of the programm so it wrote empty strings even when using the get method.

DracoTomes
  • 21
  • 3