Home > Software design >  why does split method stop working with Tkinter?
why does split method stop working with Tkinter?

Time:06-19

Whenever I run this code with the chopped = first_word.split() line I get an error (the window closes instantly).

import tkinter as tk

win = tk.Tk()
win.title("Conversation")
win.iconbitmap("cake.ico")
win.geometry("600x700")
#Lists
Hellos = ["greetings", 'hello', 'greetings', 'hi']
gday = ['good', 'great', 'incredible', 'not bad', 'okay']
bday = ['bad', 'awful', 'not the best', 'terrible']

fw_label = tk.Label(win, text="Hello user, it's nice to meet you.")
fw_label.pack()
first_word = tk.Entry()
first_word.pack()
chopped = first_word.split()

But when I change the line first_word = tk.Entry() to first_word="A normal string" , the split method highlights and when I hover it it gives its description, which wasn't happening with ```first_word = tk.Entry()``.

I've ran into this problem when using libraries like opencv, may I know what's causing it not to work?

CodePudding user response:

The solution is simple. You have to make a function to be called while pressing the submit button. And the statement chopped = first_word.get().split() should be inside that function.

Coming to the error part, it was because first_word is a tkinter entry object without any attribute split(). The split method works only for strings. To get the text entered into the entry widget in form of string, you need to use the get() method...

import tkinter as tk

def click():
    chopped = first_word.get().split()
    print(chopped)

win = tk.Tk()
win.title("Conversation")
# win.iconbitmap("cake.ico")
win.geometry("600x700")
#Lists
Hellos = ["greetings", 'hello', 'greetings', 'hi']
gday = ['good', 'great', 'incredible', 'not bad', 'okay']
bday = ['bad', 'awful', 'not the best', 'terrible']

fw_label = tk.Label(win, text="Hello user, it's nice to meet you.")
fw_label.pack()
first_word = tk.Entry()
first_word.pack()
tk.Button(win, text="Submit", command=click).pack()

win.mainloop()

So, you get the text of the entry using the get() method and then split it

Note : The statement chopped = first_word.get().split() should be inside the function because if its outside it, it would be executed at the time of the creation of the entry widget and using get() there would result in an empty value as the entry doesn't contain anything at that point

CodePudding user response:

Maybe this could work

Change

chopped = first_word.split()

to

chopped = first_word.get().split()
  • Related