Reputation: 15
Please check the following code;when pressing the add button,the value of text entered in the box, must be entered and printed out using the add function
my olde code used to return PY_VAR1 value for the entrybox , here's a link for my old code My entry box always returns PY_VAR1 value!!though I'm using the .get function
from Tkinter import *
root = Tk()
class Addcase:
def mains(self):
master = Tk()
master.wm_title("Add")
self.content = StringVar()
self.text = StringVar()
self.bz = Button(master,text="add",command=self.add)
self.bz.pack()
self.l = Label(master,text="ok")
self.l.pack()
self.e = Entry(master,textvariable=self.content)
self.e.pack()
print self.content.get() + "hello"
master.mainloop()
def add(me):
print "this is the entered text"
print me.content.get()
def calladd():
z = Addcase()
z.mains
def main():
calling = Addcase()
root.wm_title("Hello, me")
b = Button(root, text="Add a case",command=calling.mains)
b.pack()
mainloop()
if __name__ == '__main__':
main()
Upvotes: 1
Views: 116
Reputation: 365607
The problem here is that you're creating two roots, by calling Tk()
twice. You can't do that; if you do, all kinds of odd things happen.
In this case, the odd thing that happened is that self.content
ended up being part of the first root, which doesn't get a chance to run until the second root finishes its mainloop
. So, the StringVar
contents were never getting updated.
(If you looked carefully, you'd also notice that the original window didn't respond properly to events. That has a different effect on different platforms—anything from not refreshing its display if you drag another window across it, to looking fully responsive but not actually doing anything when you click the button until after you've closed the second window.)
If you want to create a new top-level window that runs in the same main loop as the root, you do that by using Toplevel
.
So, at the top of Addcase.mains
, instead of doing master = Tk()
, do master = Toplevel()
. And then, at the bottom, remove that master.mainloop()
call.
However, it would really be better to follow a more standard idiomatic pattern for Tkinter. You have a class that's just being used as a holder for that mains
function. Constructing an instance of the class doesn't do anything; calling that function does everything. It would be clearer to either write the function as a function (in which case add
would be a local function within that function), or write a class that initializes things in its __init__
(and possibly inherits from Toplevel
instead of containing it). Look through the examples in the docs for how to do each way.
Upvotes: 1