I have just started using Tkinter and trying to create a simple pop-up box in python. I have copy pasted a simple code from a website:
from Tkinter import *
master = Tk()
Label(master, text="First Name").grid(row=0)
Label(master, text="Last Name").grid(row=1)
e1 = Entry(master)
e2 = Entry(master)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
mainloop( )
This code is taking really long time to run, it has been almost 5 minutes!
Is it not possible to just run this snippet?
Can anybody tell me how to use Tkinter?
I am using jupyter notebook and python version 2.7. I would request a solution for this version only.
Your code is working just fine. Nevertheless for those using python3 module name has changed from Tkinter to tkinter all in lowercase. Edit the name and you're good to go!
In a nutshell.
python2:
from Tkinter import *
python3:
from tkinter import *
Look at the screenshot below
from Tkinter import *
def printData(firstName, lastName):
print(firstName)
print(lastName)
root.destroy()
def get_input():
firstName = entry1.get()
lastName = entry2.get()
printData(firstName, lastName)
root = Tk()
#Label 1
label1 = Label(root,text = 'First Name')
label1.pack()
label1.config(justify = CENTER)
entry1 = Entry(root, width = 30)
entry1.pack()
label3 = Label(root, text="Last Name")
label3.pack()
label1.config(justify = CENTER)
entry2 = Entry(root, width = 30)
entry2.pack()
button1 = Button(root, text = 'submit')
button1.pack()
button1.config(command = get_input)
root.mainloop()
Copy paste the above code into a editor, save it and run using the command,
python sample.py
Note: The above code is very vague. Have written it in that way for you to understand.
You can create a popup information window as follow:
showinfo("Window", "Hello World!")
If you want to create a real popup window with input mask, you will need to generate a new TopLevel mask and open a second window.
win = tk.Toplevel()
win.wm_title("Window")
label = tk.Label(win, text="User input")
label.grid(row=0, column=0)
button = ttk.Button(win, text="Done", command=win.destroy)
button.grid(row=1, column=0)
check it again the code is executing properly but u can't see that output in jupyter notebook itself u can see it in windows column like beside the chrome icons in toggle bar .I'm also confused initially check it once
Related
I have successfully created a GUI that takes user input and gives the desired output, but I can't seem to figure out how to display this output in another window instead of just in the IDE console. My goal is to have a window pop up with the output once the user clicks 'Compute BMI', but as of right now, the output only shows in the console. I have looked for solutions but I can't seem to figure out what tools I can use to make this happen. I am new to GUIs so any help would be much appreciated.
from tkinter import *
root = Tk()
def myBMI():
weight = float(Entry.get(weight_field))
height = float(Entry.get(height_field))
bmi = (weight*703)/(height*height)
print(bmi)
height_label = Label(root, text="Enter your height: ")
height_field = Entry(root)
height_field.grid(row=0, column=1)
height_label.grid(row=0, sticky=E)
weight_label = Label(root, text="Enter your weight: ")
weight_field = Entry(root)
weight_field.grid(row=1, column=1)
weight_label.grid(row=1, sticky=E)
compute_bmi = Button(root, text="Compute BMI", command=myBMI)
compute_bmi.grid(row=2)
root.mainloop()
tkinter "pop-ups" should typically be handled via the tk.TopLevel() method! This will generate a new window that can be titled or have buttons put in it like:
top = Toplevel()
top.title("About this application...")
msg = Message(top, text=about_message)
msg.pack()
button = Button(top, text="Dismiss", command=top.destroy)
button.pack()
So instead of print(bmi) you could do something like, say:
top = tk.Toplevel()
msg = tk.Label(top, text=bmi)
msg.pack()
More documentation can be found at http://effbot.org/tkinterbook/toplevel.htm!
So I have been using python to do my 'ETLs' from SQL to Excel or CSV. I have just found it to be faster and easier than using SSIS.
While I do this in Jupyter I thought it would be a fun exercise to package this into an app that I can share with others. I'm not the most versed in tkinter and am trying to add a custom sized textbox that would be a little nicer than standard textbox for copy/pasting query. The issue is when I add the textbox, it instead adjusts the settings for the app window.
Here is what I have so far:
#Load Libraries
import pandas as pd
import numpy as np
import pyodbc
import xlsxwriter
from pandas import ExcelWriter
import openpyxl
import os
import datetime
from tkinter import *
#create window
def conVar():
server = e1.get()
db = e2.get()
un = e3.get()
pw = e4.get()
conn=("DRIVER={SQL Server};SERVER=%s;DATABASE=%s;UID=%s;PWD=%s" % (server, db, un, pw))
print(conn)
root = Tk()
root.title("SQL2Excel")
root.geometry("500x500")
Label(root, text="Server").grid(row=0)
Label(root, text="Database").grid(row=1)
Label(root, text="Username").grid(row=2)
Label(root, text="pw").grid(row=3)
Label(root, text="Tables").grid(row=6)
Label(root, text="or Enter Query").grid(row=7)
variable = StringVar(root)
variable.set(" ")
w = OptionMenu(root, variable, "test1", "test2", "test3")
r = root
r.geometry("250x150")
t = Text(r, height=20, width=40)
e1 = Entry(root)
e2 = Entry(root)
e3 = Entry(root)
e4 = Entry(root, show="*")
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)
e4.grid(row=3, column=1)
w.grid(row=6, column=1)
t.grid(row=8, column=1)
Button(root, text='Quit', command=root.destroy).grid(row=4, column=0, sticky=W, pady=4)
Button(root, text='Test Connection', command=conVar).grid(row=4, column=1, sticky=W, pady=4)
root.mainloop()
The idea is that once connection info is entered I will pull a list of tables into the combobox or let the user copy and paste a query into the larger text box. I really feel like I'm missing something easy but struggling at this point.
Can someone help show me the error of my ways? Thank you.
Your code is change the size of the root window
root.title("SQL2Excel")
root.geometry("500x500")
r = root
r.geometry("250x150")
Instead, try changing the geometry of the Combobox.
Also, I do not see a Combobox in your code
I'm making a GUI with python and tkinter That prompts user the Mac Address of his pc and asks for a code The Python snippet i have used for retrieving the MAc address is :
import uuid
def get_mac():
mac_num = hex(uuid.getnode()).replace('0x', '').upper()
mac = ''.join(mac_num[i : i + 2] for i in range(0, 11, 2))
return mac
x= get_mac()
print x
I have also made a gui containing the two fields as shown below
However when i execute the python snippet the mac address is displayed outside the python gui and in the python shell, how can i make the mac address appear in the space provided in the GUi itself
Here is the code for the gui:
from Tkinter import *
from ttk import *
root =Tk()
def show_form():
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
b = Button(bottomFrame,text="ACTIVATE",command=lambda: show_call_back(root))
b1 = Button(bottomFrame, text="TRIM")
b2 = Button(bottomFrame, text="OVERLAY")
b3 = Button(bottomFrame, text="MERGE")
b.pack(side=RIGHT,padx=8,pady=26)
b1.pack(side=LEFT, padx=8, pady=26)
b1.config(state='disabled')
b2.pack(side=LEFT, padx=8, pady=26)
b2.config(state='disabled')
b3.pack(side=LEFT, padx=8, pady=26)
b3.config(state='disabled')
root.mainloop()
def show_call_back(parent):
top = Toplevel(parent)
top.geometry("250x200+600+250")
top.resizable(width=False, height=False)
top.title("Activation")
Label(top, text="Mac Address:",).grid(row=0, sticky=W, padx=4)
Label(top, text="Code").grid(row=1, sticky=W, padx=4)
Entry(top).grid(row=1, column=1, sticky=E, pady=4)
Button(top, text="Submit", command=top.destroy).grid(row=2, column=1)
show_form()
root.mainloop()
After your last comment, the solution is quite simple: add a new Label to display the result of get_mac().
Solution - Add a Label in row=0 and text=get_mac().
hLbl = Label(top, text=get_mac(), bg='white', relief=SUNKEN, width = 15)
hLbl.grid(row=0, column=1, sticky=E, pady=4)
I have added bg='white' and relief=SUNKEN to a the same style as
an Entry. The extra width = 15 is to enlarge the size of the label.
Warning 1 - as #abccd comments, keep only one mainloop(), and place the root = Tk() after the function declaration.
Warning 2 - Instead of using root as a global variable in bottomFrame = Frame(root) of the function show_form(), add it as input parameter.
def show_form(my_root): # use my_root instead of global root
bottomFrame = Frame(my_root)
bottomFrame.pack(side=BOTTOM)
# also for the command parameter
b = Button(bottomFrame,text="ACTIVATE",command=lambda: show_call_back(my_root))
...
And call:
root = Tk()
show_form(root)
root.mainloop()
EDIT -------
Output - here is what I get under Python 3.5.0
I am trying to create a window with Tkinter but no window is being created and I am not receiving any error codes?
from tkinter import *
def login_window():
window=Tk()
window.title("Login")
info_lbl = Label(window)
info_lbl.grid(row=0, column=1)
username_lbl = Label(window, text='Username')
username_lbl.grid(row=1, column=1)
username_entry = Entry(window, width=10)
username_entry.grid(row=1, column=2)
password_lbl = Label(window, text='Password')
password_lbl.grid(row=2, column=1)
password_entry = Entry(window, width=10, )
password_entry.grid(row=2, column=2)
ok_button = Button(window, text='Login', command = menu_window)
ok_button.grid(row=3,column = 2,sticky =W)
Any help would be great!
Well I think u should add mainloop() inside your function as well as call your login_window something like this-
from Tkinter import *
def login_window():
window=Tk()
window.title("Login")
mainloop()
login_window()
It looks like you never entered the main Tkinter loop. To display that window, you could add this to the bottom of the function:
window.mainloop()
Take a look at this question and the accepted answer for a bit more information on the Tkinter main loop.
I'm trying to use an Entry field to get manual input, and then work with that data.
All sources I've found claim I should use the get() function, but I haven't found a simple working mini example yet, and I can't get it to work.
I hope someone can tel me what I'm doing wrong. Here's a mini file:
from tkinter import *
master = Tk()
Label(master, text="Input: ").grid(row=0, sticky=W)
entry = Entry(master)
entry.grid(row=0, column=1)
content = entry.get()
print(content) # does not work
mainloop()
This gives me an Entry field I can type in, but I can't do anything with the data once it's typed in.
I suspect my code doesn't work because initially, entry is empty. But then how do I access input data once it has been typed in?
It looks like you may be confused as to when commands are run. In your example, you are calling the get method before the GUI has a chance to be displayed on the screen (which happens after you call mainloop.
Try adding a button that calls the get method. This is much easier if you write your application as a class. For example:
import tkinter as tk
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.entry = tk.Entry(self)
self.button = tk.Button(self, text="Get", command=self.on_button)
self.button.pack()
self.entry.pack()
def on_button(self):
print(self.entry.get())
app = SampleApp()
app.mainloop()
Run the program, type into the entry widget, then click on the button.
You could also use a StringVar variable, even if it's not strictly necessary:
v = StringVar()
e = Entry(master, textvariable=v)
e.pack()
v.set("a default value")
s = v.get()
For more information, see this page on effbot.org.
A simple example without classes:
from tkinter import *
master = Tk()
# Create this method before you create the entry
def return_entry(en):
"""Gets and prints the content of the entry"""
content = entry.get()
print(content)
Label(master, text="Input: ").grid(row=0, sticky=W)
entry = Entry(master)
entry.grid(row=0, column=1)
# Connect the entry with the return button
entry.bind('<Return>', return_entry)
mainloop()
*
master = Tk()
entryb1 = StringVar
Label(master, text="Input: ").grid(row=0, sticky=W)
Entry(master, textvariable=entryb1).grid(row=1, column=1)
b1 = Button(master, text="continue", command=print_content)
b1.grid(row=2, column=1)
def print_content():
global entryb1
content = entryb1.get()
print(content)
master.mainloop()
What you did wrong was not put it inside a Define function then you hadn't used the .get function with the textvariable you had set.
you need to put a textvariable in it, so you can use set() and get() method :
var=StringVar()
x= Entry (root,textvariable=var)
Most of the answers I found only showed how to do it with tkinter as tk. This was a problem for me as my program was 300 lines long with tons of other labels and buttons, and I would have had to change a lot of it.
Here's a way to do it without importing tkinter as tk or using StringVars. I modified the original mini program by:
making it a class
adding a button and an extra method.
This program opens up a tkinter window with an entry box and an "Enter" button. Clicking the Enter button prints whatever is in the entry box.
from tkinter import *
class mini():
def __init__(self):
master = Tk()
Label(master, text="Input: ").grid(row=0, sticky=W)
Button(master, text='Enter', command=self.get_content).grid(row=1)
self.entry = Entry(master)
self.entry.grid(row=0, column=1)
master.mainloop()
def get_content(self):
content = self.entry.get()
print(content)
m = mini()