Valentin Rafael
Valentin Rafael

Reputation: 13

Get text from Tkinter entry search box with a button

I'm pretty new to python and I just started with Tkinter. I'm trying to make some self-exercise files. So far so good, but I went into a problem ( I will post the whole code and after I'll continue with the problem so that you can see what I want to make and where I do not understand how to do).

#!/usr/bin/python

from tkinter import *
from PIL import Image, ImageTk
import subprocess



class Window(Frame):
 def __init__(self, master = None):
  Frame.__init__(self, master)
  self.master = master
  self.init_window()

 def init_window(self):
  self.master.title("ez-Installer")
  self.pack(fill=BOTH, expand=1)

  updateButton = Button(self, text="Update", command=self.system_update)
  updateButton.place(x=50, y=50)

  syncButton = Button(self, text="Sync packages", command=self.system_sync)
  syncButton.place(x=150, y=50)

  cmd1 = StringVar()
  mEntry = Entry(self,textvariable=cmd1).pack()

  installButton = Button(self, text="Install", command=self.system_install)
  installButton.place(x=50, y=150)

 def system_install(self):
  package = cmd1.get()
  install = "sudo pacman -S {} --noconfirm".format(package)
  subprocess.call([install], shell=True)

 def system_exit(self):
  exit()

 def system_update(self):
  subprocess.call(["sudo pacman -Su --noconfirm"], shell=True)

 def system_sync(self):
  subprocess.call(["sudo pacman -Syy --noconfirm"], shell=True)


root = Tk()
root.geometry("400x300")
app = Window(root)

root.mainloop()

The error is when pressing "Install" button. "cmd1 is not defined".

def system_install(self):
 package = cmd1.get()
 install = "sudo pacman -S {} --noconfirm".format(package)
 subprocess.call([install], shell=True)

As you can see, I want it to get text from the search box Entry that I added here:

  cmd1 = StringVar()
  mEntry = Entry(self,textvariable=cmd1).pack()

  installButton = Button(self, text="Install", command=self.system_install)
  installButton.place(x=50, y=150)

I know that my entry is under the def init_window(self): , but how can I grab the value of cmd1 from there? Is it possible? If not or if it is too much of a hassle, what would an similar alternative be?

Upvotes: 1

Views: 2988

Answers (1)

patthoyts
patthoyts

Reputation: 33223

In your system_install method you have no access to the cmd1 variable as you did not attach it to the object instance. You just created it as a local variable in the init_window method. To fix that, use self.cmd1 in each place to make it an instance variable that is visible to all method via the self argument.

A separate problem is mEntry will be define to None as the pack() method does not return anything. I suspect what you mean to do there should be:

self.cmd1 = StringVar()
self.mEntry = Entry(self,textvariable=self.cmd1)
self.mEntry.pack()

Upvotes: 1

Related Questions