How to add a custom tkinter textbox in my Python app? - python

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

Related

How can I append elements inputted by user in a tk.Entry object into a list?

I'm trying to build a very simple program in Python and Tkinter that allows the user to input people's names by keyboard and then a button is commanded to select a person from the list at random and show it in a tk.Label object.
My problem is once I run the root.mainloop(), I can add names to the list but the list does not update with the new names.
This is the main code for the Tkinter to initialize
import tkinter as tk
from tkinter import filedialog, Text
import random
root = tk.Tk()
root.title('Millor persona del moment')
root.geometry("500x200")
root.configure(bg='black')
peopleList = []
tk.Label(root, text="Insertar participante: ",fg="#ff007f", bg='black').grid(row=0)
e1 = tk.Entry(root)
e1.grid(row=0, column=1)
addButton = tk.Button(root, text='AƱadir', padx=10, pady=5, fg="#ff007f", bg='black', command=addPerson)
addButton.grid(row=0, column=2)
while peopleList:
turnButton = tk.Button(root, text='Saca Tema', padx=10, pady=5, fg="#ff007f", bg='black', command=wordTurn(peopleList))
turnButton.grid(row=1, column=0)
nom = tk.StringVar()
nom.set('Comencem')
personSpeaking = tk.Label(root, textvariable=nom,fg="#ff007f", bg='black')
personSpeaking.grid(row=1, column=1)
root.mainloop()
And these are the functions I use
def addPerson():
peopleList.append(e1.get())
e1.delete(0,'end')
def wordTurn(peopleList):
person = random.choice(peopleList)
peopleList.remove(person)
nom.set(person)
command=wordTurn(peopleList)) calls the return value of wordTurn when the button is pressed, which is None and should raise an error. Use command=lambda peopleList=peopleList: wordTurn(peopleList)) instead.

Copying text in tkinter from label or msgbeox

I been searching for methods to copy text to clipboard or copy the results from Tkinter gui but idk if there is a command or something
here is my code for now here the result comes in a messagebox can i copy it to clipboard
import tkinter.messagebox
import string
import random
def qs_msgbbox(): # qs_msgbbox
tkinter.messagebox.showinfo("Info", "For customer support or tip or rating contact:"
"dghaily725#gmail.com\npress the button for generated pass\nmsg will appear then copy\nthe generated password")
def gen_pass(k=9): # gen_pass
char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*"
password = ''
for i in range(9):
password += random.choice(char)
tkinter.messagebox.showinfo("Password", password)
root = Tk()
root.title("Password Generator")
lbl1 = Label(root, text="Generate Password", bd=2, relief=SUNKEN, height=5, width=50, bg='black', fg='white')
lbl1.configure(font=(70))
lbl1.grid(row=0, column=2)
lbl2 = Label(root, text='For more information press the Question mark', bd=2, relief=SUNKEN, fg='red')
lbl2.configure(font=(70))
lbl2.grid(row=0, column=0, pady=10)
btn1 = Button(root, text='Press to Generate', height=5, width=50, bg='grey', command=gen_pass)
btn1.configure(font=(70))
btn1.grid(row=1, column=2, padx=460, pady=50)
btn2photo = PhotoImage(file='question.png')
btn2 = Button(root, image=btn2photo, width=30, height=30, command= qs_msgbbox)
btn2.grid(row=0, column=1)
root.mainloop()
and also just a quick small question is it better to use classes or this form
Tkinter does have a function for that, simply just
from tkinter import Tk
root = Tk()
root.clipboard_clear()
root.clipboard_append("Something to the clipboard")
root.update() # the text will stay there after the window is closed
Hope I could help
Greets
The above answer is perfectly fine. Infact its the method to do it. I read the comments, He had mentioned that it could only take in string. That is completely false. It can also take in functions. For example..
import tkinter as tk
root = tk.Tk()
#creating a entry Widget.(Labels are fine as well)
entry = tk.Entry(root)
entry.pack()
#NOW if you want to copy the whole string inside the above entry box after you
typed in #
def copy ():#assign this function to any button or any actions
root.clipboard_clear()
root.clipboard_append(entry.get()) #get anything from the entry widget.
root.mainloop()
Hoping this was helpful

Python Tkinter GUI messy printing format

import pandas as pd
import csv
from tkinter import *
master = Tk()
textBox = Text(master, height=1, width=10)
textBox.grid(row=0, column=1)
fileVar = StringVar()
fileLabel = Label(master, textvariable=fileVar)
fileLabel.grid(row=3, column=1)
fileVar2 = StringVar()
fileLabel2 = Label(master, textvariable=fileVar)
fileLabel2.grid(row=3, column=2)
def retrieve_input():
Customer = textBox.get("1.0","end-1c")
fileread = pd.read_csv('50.csv', encoding='latin-1')
filevalue = fileread.loc[fileread['Customer'].str.contains(Customer, na=False),"Jul-18\nQty"]
productheader = fileread.loc[fileread['Customer'].str.contains(Customer, na=False), 'Product']
fileVar.set(productheader)
fileVar2.set(filevalue)
button1 = Button(master,text="Show Values", command=lambda: retrieve_input())
button1.grid(row=4, column=1)
mainloop()
I have this program that prints values in Tkinter Gui, for specific values in a specific row. However the format of the values being printed is quiet messy and I am unsure how to clean it up, In addition I would like for it to not display the numbers labeled next to it, Just the product name (blurred out in blue) and the value associated with it( which are the number values with decimals).
Here is a snapshot of the GUI:
In addition, at the very bottom of the list, this is also displayed:
Ideally, I would like for it to only show the header(July-18) and not the datatype
Also if it helps to know, these are forecast files, (reason for headers with dates)
Here is a dummy image of what my csv files look like:
Ok so after some testing I think I have found a fix that should work for you.
The main issue with spacing inside of your label is the problem with your font not being one that is considered monospace.
Try using the font Consolas and see how well that fixes your layout.
import pandas as pd
from tkinter import *
master = Tk()
textBox = Text(master, height=1, width=10, font=('Consolas', 12))
textBox.grid(row=0, column=1)
fileVar = StringVar()
fileLabel = Label(master, textvariable=fileVar, font=('Consolas', 12))
fileLabel.grid(row=3, column=1)
def retrieve_input():
department = textBox.get("1.0","end-1c")
fileread = pd.read_csv('50.csv', encoding='latin-1')
filevalue = fileread.loc[fileread['Customer'].str.contains(department, na=False),("Jul-18\nQty", "Product")]
fileVar.set(filevalue)
button1 = Button(master,text="Show Values", command=lambda: retrieve_input())
button1.grid(row=4, column=1)
master.mainloop()

Using Tkinter in Jupyter Notebook

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

Tkinter not creating a window?

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.

Categories

Resources