How to export inputted parameters with python tkinter? - python

I apologies because I'm a new user for python tkinter.
It is possible to export data inputted with Entry function?
Currently the code works, but the value is not present in the "e1" output.
Thanks in advance
try:
import Tkinter as tk
except:
import tkinter as tk
class Test():
def __init__(self):
self.root = tk.Tk()
self.root.geometry('100x50')
e1 = tk.Entry(self.root)
e1.pack()
self.e1 = e1.get()
button = tk.Button(self.root,
text = 'Quit and take out values',
command=self.quit)
button.pack()
self.root.mainloop()
def quit(self):
self.root.destroy()
app = Test()
print(app.e1)

You call e1.get() right after e1 is created. So at that time there is nothing input and you should get an empty string.
You can get the entry value inside quit() function, but you need to rename e1 to self.e1:
try:
import Tkinter as tk
except:
import tkinter as tk
class Test():
def __init__(self):
self.root = tk.Tk()
self.root.geometry('100x50')
self.e1 = tk.Entry(self.root)
self.e1.pack()
button = tk.Button(self.root,
text = 'Quit and take out values',
command=self.quit)
button.pack()
self.root.mainloop()
def quit(self):
self.value = self.e1.get()
self.root.destroy()
app = Test()
print(app.value)

Related

How to run a function as a button command in tkinter from a 2nd window

Hi I am pretty new to tkinter and have being trying to create a button that opens a window then a have a button in the new window the gives a message when pressed. I ran into the problem that the only whay I could get it to recognise the function I wrote was to write it inside the function that opens the second window. I don't know if I have being searching for the wrong things but I can't find how to do this properly. Can someone help me out Here is my code
from tkinter import *
master = Tk()
master.title("frame control")
def win():
window2 = Toplevel()
def open():
stamp = Label(window2, text="Staped").pack()
lab2 = Button(window2,text = "yo ",command = open).pack()
lab1 = Button(master,text = " open a new window" , command = win).pack()
mainloop()
This is your code but with best practises:
import tkinter as tk
def create_stamp():
stamp = tk.Label(window2, text="Stamp")
stamp.pack()
def create_second_win():
global window2
window2 = tk.Toplevel(root)
lab2 = tk.Button(window2, text="Click me", command=create_stamp)
lab2.pack()
root = tk.Tk()
root.title("Frame control")
button = tk.Button(root, text="Open a new window", command=create_second_win)
button.pack()
root.mainloop()
I made window2 a global variable so that I can access it from create_stamp. Generally it is discouraged to use from ... import *. As #Matiiss said, sometimes you can have problems with global variables if you don't keep track of the variable names that you used.
If you want to avoid using global variables and want to use classes, look at this:
import tkinter as tk
class App:
def __init__(self):
self.stamps = []
self.root = tk.Tk()
self.root.title("Frame control")
self.button = tk.Button(self.root, text="Open a new window", command=self.create_second_win)
self.button.pack()
def create_stamp(self):
stamp = tk.Label(self.window2, text="Stamp")
stamp.pack()
self.stamps.append(stamp)
def create_second_win(self):
self.window2 = tk.Toplevel(self.root)
self.lab2 = tk.Button(self.window2, text="Click me", command=self.create_stamp)
self.lab2.pack()
def mainloop(self):
self.root.mainloop()
if __name__ == "__main__":
app = App()
app.mainloop()
As #Matiiss mentioned it would be more organised if you move the second window to its own class. For bigger projects it is a must but in this case you don't have to.

tkinter button in class won't bind to key

Total noob can't make tkinter button bind to keyboard.
I've tried to bind they both in main() and in the init().
I've tried bunches of permutations of syntax. Nothing works.
I've tried around until the button(s) get focus and hitting then. NOTHING HAPPENS.
Anyone have the secret insider information on how to do it?
from tkinter import *
from tkinter.ttk import Frame, Button, Style
class Example(Frame):
def __init__(self):
super().__init__()
self.initUI()
self.btn_convert.bind("<Return>", self.convert)
# -----------------------------------------------
def convert(self):
print("enter pressed")
# -----------------------------------------------
def quit(self):
self.root.destroy()
exit()
# -----------------------------------------------
def initUI(self):
self.master.title("Weight Converter")
self.pack(fill=BOTH, expand=True)
self.frame_btn = Frame(self)
self.frame_btn.pack(fill=BOTH, expand=True, padx=20, pady=5)
self.btn_convert=Button(self.frame_btn, text="Convert", command=self.convert)
self.btn_convert.pack(side=LEFT, padx=5, pady=5)
self.btn_close1=Button(self.frame_btn, text="Close", command=quit)
self.btn_close1.pack(side=LEFT, padx=5, pady=5)
def main():
root = Tk()
root.geometry("300x250+300+200")
app = Example()
root.bind("<Return>", lambda event: root.convert())
root.mainloop()
if __name__ == '__main__':
main()
Replace:
root.bind("<Return>", lambda event: root.convert())
with:
root.bind("<Return>", lambda event: app.convert())
or:
#in case you have multiple instances of Tk
app.bind("<Return>", lambda event: app.convert())
app.focus_set()
As convert is a method for Example instance(app) as opposed to Tk instance(root). Also, make sure that the object.bind is used on(root in above two lines and app onthe last line) has the focus by either manually focusing or calling object.focus_set().
Below is an example that prints "Enter" or "Escape" based on the keypress:
import tkinter as tk
class App(tk.Frame):
def __init__(self, master):
super().__init__(master)
self.button = tk.Button(self, text="Event")
self.button.bind('<Return>', lambda evt : self.event_handler(True))
self.button.focus_set() # ensure initial focus is on the button
self.button.pack()
def event_handler(self, is_enter):
if is_enter:
my_string = "Enter"
else:
my_string = "Escape"
print(my_string)
if __name__ == '__main__':
root = tk.Tk()
app = App(root)
app.button.bind('<Escape>', lambda evt : app.event_handler(False))
app.pack()
root.mainloop()
Demo Example for all keys
Below demo should be displaying the pressed key for all keys:
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
def on_key_press(event):
global label
label['text'] = event.keysym
if __name__ == '__main__':
root = tk.Tk()
label = tk.Label(root)
root.bind('<KeyPress>', on_key_press)
label.pack()
root.mainloop()
To add a general "press Enter to run convert" binding, you should apply it to root. To add further focus-based bindings, you should apply them on a per-button basis, like so:
from tkinter import *
from tkinter.ttk import Frame, Button, Style
class Example(Frame):
def __init__(self):
super().__init__()
self.initUI()
# -----------------------------------------------
def convert(self):
print("enter pressed")
# -----------------------------------------------
def quit(self):
print("quit pressed")
self.destroy()
exit()
# -----------------------------------------------
def initUI(self):
self.master.title("Weight Converter")
self.pack(fill=BOTH, expand=True)
self.frame_btn = Frame(self)
self.frame_btn.pack(fill=BOTH, expand=True, padx=20, pady=5)
self.btn_convert=Button(self.frame_btn, text="Convert", command=self.convert)
self.btn_convert.pack(side=LEFT, padx=5, pady=5)
self.btn_close1=Button(self.frame_btn, text="Close", command=quit)
self.btn_close1.pack(side=LEFT, padx=5, pady=5)
# When tab focus is on the "Close" button, change Return behaviour.
self.btn_close1.bind("<Return>", lambda event: self.quit())
def main():
root = Tk()
root.geometry("300x250+300+200")
app = Example()
root.bind("<Return>", lambda event: app.convert())
root.mainloop()
if __name__ == '__main__':
main()

I can't create a second window using tkinter, on os x

When creating a second window using python 3.6 and tkinter, it is not responsible. I`m using os x 10.11.6.
In other systems such as Ubuntu, this code works.
from tkinter import *
class win2:
def __init__(self):
self.root = Tk()
self.root.mainloop()
class win1:
def __init__(self):
self.root = Tk()
self.button = Button(self.root)
self.button.bind('<Button-1>', self.buttonFunc)
self.button.pack()
self.root.mainloop()
def buttonFunc(self, event):
windows2 = win2()
if __name__ == "__main__":
window1 = win1()
It's a very bad idea to use Tk() more than once in your program. Use it to make the root window, and then use Toplevel() to make any additional windows.
def buttonFunc(self, event):
Toplevel(self.root)
That said, it still looks like you are trying to do something the hard way. Can you describe better what your end goal is?
To make a modal window (a popup) use code like this:
try: #python3 imports
import tkinter as tk
except ImportError: #python3 failed, try python2 imports
import Tkinter as tk
class Main(tk.Frame):
def __init__(self, master=None, **kwargs):
tk.Frame.__init__(self, master, **kwargs)
lbl = tk.Label(self, text="this is the main frame")
lbl.pack()
btn = tk.Button(self, text='click me', command=self.open_popup)
btn.pack()
def open_popup(self):
print("runs before the popup")
Popup(self)
print("runs after the popup closes")
class Popup(tk.Toplevel):
"""modal window requires a master"""
def __init__(self, master, **kwargs):
tk.Toplevel.__init__(self, master, **kwargs)
lbl = tk.Label(self, text="this is the popup")
lbl.pack()
btn = tk.Button(self, text="OK", command=self.destroy)
btn.pack()
# The following commands keep the popup on top.
# Remove these if you want a program with 2 responding windows.
# These commands must be at the end of __init__
self.transient(master) # set to be on top of the main window
self.grab_set() # hijack all commands from the master (clicks on the main window are ignored)
master.wait_window(self) # pause anything on the main window until this one closes
def main():
root = tk.Tk()
window = Main(root)
window.pack()
root.mainloop()
if __name__ == '__main__':
main()
This code works for me.
from tkinter import *
class win1:
def __init__(self):
root = Tk()
button = Button(root)
button.bind('<Button-1>', self.buttonFunc)
button.pack()
root.mainloop()
def buttonFunc(self, event):
window2 = win2()
class win2(win1):
def __init__(self):
top = Toplevel()
if __name__ == "__main__":
window1 = win1()

Python tkinter checkbutton value not accessible

I want to build a little GUI application in Python. The goal is to have a main window calling several other windows. In one of these called windows I have a checkbutton. My problem is that I cannot read the value of this checkbutton, whereas I can read the value of an Entry widget. What am I doing wrong?
from tkinter import *
import tkinter as tk
class mainwindow():
def __init__(self, master):
self.master = master
menubalk = Menu(self.master)
menubalk.add_command(label="New window", command=self.openNewwindow)
self.master.config(menu=menubalk)
def openNewwindow(self):
window = newwindow()
window.mainloop()
class newwindow(Tk):
def __init__(self):
Tk.__init__(self)
self.var = BooleanVar()
self.checkbutton = Checkbutton(self, text="Check", variable=self.var)
self.checkbutton.grid(column=0, row=0)
self.var2 = StringVar()
self.entry = Entry(self, textvariable=self.var2)
self.entry.grid(column=2,row=0)
self.button2 = Button(self,text=u"Show", command=self.showValues).grid(column=1, row=0)
def showValues(self):
print('Value checkbutton:', self.var.get(), ';', 'Value entryfield: ', self.entry.get())
def main():
root = Tk()
window = mainwindow(root)
root.mainloop()
if __name__ == '__main__':
main()
You are making multiple, separate Tkinter applications in your program. Do not do that. To create new windows, use the Toplevel widget.
from tkinter import *
class mainwindow():
def __init__(self, master):
self.master = master
menubalk = Menu(self.master)
menubalk.add_command(label="New window", command=self.openNewwindow)
self.master.config(menu=menubalk)
def openNewwindow(self):
def showValues(var, entry):
print('Value checkbutton:', var.get(), ';', 'Value entryfield: ', entry.get())
window = Toplevel(self.master)
var = BooleanVar()
checkbutton = Checkbutton(window, text="Check", variable=var)
checkbutton.grid(column=0, row=0)
var2 = StringVar()
entry = Entry(window, textvariable=var2)
entry.grid(column=2,row=0)
button2 = Button(window,text=u"Show", command=lambda: showValues(var, entry))
button2.grid(column=1, row=0)
def main():
root = Tk()
window = mainwindow(root)
root.mainloop()
if __name__ == '__main__':
main()
Tkinter's variable objects (IntVar, StringVar, etc.) must take argument "master" as their firs parameter. i.e. replace
self.var=StringVar()
With
self.var=StringVar(self)
Or
self.var=StringVar(master=self)

Python: Tkinter OK button callback function

I'm working on my very first Python GUI and I'm trying to modify this tkinter example, but I simply cannot figure out how to write a callback function for the OK button that will pass on the entered value to the main program.
#!/usr/bin/python
# -*- coding: utf-8 -*-
from Tkinter import Tk, BOTH, StringVar, IntVar
from ttk import Frame, Button, Style, Label, Entry
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Get Value")
self.style = Style()
self.style.theme_use("default")
self.pack(fill=BOTH, expand=1)
valueLabel = Label(self, text="Value: ")
valueLabel.place(x=10, y=10)
value=StringVar(None)
value.set("this is the default value")
valueEntry=Entry(self, textvariable=value)
valueEntry.place(x=70, y=10)
quitButton = Button(self, text="Quit", command=self.quit)
quitButton.place(x=10, y=50)
okButton = Button(self, text="OK", command=self.quit)
okButton.place(x=120, y=50)
def main():
root = Tk()
root.geometry("220x100+300+300")
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
I've read a gazillion of tutorials, but none of them explains this clearly. Theoretically, I should be able to get the selected value with value.get(), but I keep getting error messages no matter where I put it. Also, AFAIK, I should be able to define a default value with value.set(), but this doesn't seem to have an effect, since the text box is empty when I run the program.
What is the easiest way to pass on values to the main python program after root.mainloop() terminates? (The actual dialog box contains several entry boxes for entering string and integer values.)
I.e. I want to be able to use something like:
root = Tk()
root.geometry("220x100+300+300")
app = Example(root)
root.mainloop()
print value
print value2
print value3
How do I define default values for entry boxes?
Change every occurrence of the value variable with self.value. This should fix it and the default value will be displayed.
UPDATE
from Tkinter import Tk, BOTH, StringVar, IntVar
from ttk import Frame, Button, Style, Label, Entry
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def showMe(self):
print(self.value.get())
def initUI(self):
self.parent.title("Get Value")
self.style = Style()
self.style.theme_use("default")
self.pack(fill=BOTH, expand=1)
valueLabel = Label(self, text="Value: ")
valueLabel.place(x=10, y=10)
self.value=StringVar(None)
self.value.set("this is the default value")
valueEntry=Entry(self, textvariable=self.value)
valueEntry.place(x=70, y=10)
quitButton = Button(self, text="Quit", command=self.quit)
quitButton.place(x=10, y=50)
okButton = Button(self, text="OK", command=self.showMe)
okButton.place(x=120, y=50)
def main():
root = Tk()
root.geometry("220x100+300+300")
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
Both your quitButton and okButton call the self.quit functions. So no mater what value you enter when you press the OK button you are calling the quit function which has its own problems as well outside the scope of your question.
Try to define value as self.value and make the okButton call a function that does: print self.value.get().

Categories

Resources