python 3.5 tkinter text box recording - python-3.x

I have created a program that to record the input in a text box. After that, it would print it in a text
Here is the code:
from tkinter import*
window = Tk()
window.geometry("500x300")
a = Label(window, text="hi", font=('Helvetica', 32))
a.place(x=70, y = 80)
entry_box2=Entry(window,)
entry_box2.place(x=110, y=100)
def retrieve_input():
input = entry_box2.get("1.0",'end-1c')
a = Label(window, text= input, font=('Helvetica', 32))
a.place(x=70, y = 80)
window.mainloop()
I hope I could get a response as fast as posiblle

You have to use retrieve_input. You can bind() it to Entry and execute when Enter is pressed.
entry_box2.bind('<Return>', retrieve_input)
And then you can add new Label or replace text in existing one.
import tkinter as tk
# --- functions ---
def retrieve_input(event):
# get text from Entry
#txt = ent.get()
txt = event.widget.get()
# create new label with text
l = tk.Label(root, text=txt)
l.pack()
# or change existing label
lab['text'] = txt
# clear entry
#ent.delete(0, len(txt))
event.widget.delete(0, len(txt))
# --- main ---
root = tk.Tk()
lab = tk.Label(root, text="Hello")
lab.pack()
ent = tk.Entry(root)
ent.pack()
ent.bind('<Return>', retrieve_input)
root.mainloop()

Related

Background Image Adjustment on Top Level Window with Tkinter

I have a basic GUI that begins with a main menu of sorts. I have successfully set a background image to that menu and it also scales when I change the dimension of the GUI window.
However when I try to define some top-level windows that are opened by the sub-menu items the background image does not appear (not to mention scale).
Not sure what I'm doing wrong but I'm attaching the code I wrote along with the images of the basic GUI.
from tkinter import *
from tkinter import ttk, font, messagebox
from PIL import ImageTk, Image
import os
root = Tk()
root.title("Decoder of ultrasound images to detect colon tumors")
# Adding window icon
root.iconbitmap('afekaImage.ico')
rootWidth, rootHeight = 600, 600
screenWidth = root.winfo_screenwidth()
screenHeight = root.winfo_screenheight()
topLeftPosition = (screenWidth / 2 - rootWidth / 2, screenHeight / 2 - rootHeight / 2)
# Configure window size
root.geometry(f'{rootWidth}x{rootHeight}+{int(topLeftPosition[0])}+{int(topLeftPosition[1])}')
'''
# Create username & password entry
def entryDialog():
userName = entry1.get()
password = entry2.get()
if ((userName == 'Itzhak.Mamistvalov' and password == '311396832') or
(userName == 'AssafHasky' and password == '308333533')):
messagebox.showinfo('info', 'Correct Login')
else:
messagebox.showinfo('info', 'Invalid Login') '''
# open doc file
def openDocFile():
os.startfile("mid_sub.docx")
# adjusting background image to fit window
def adjustBackgroundImage(event):
# avoid garbage collection option 1
# global resizedBackgroundImage, newBackgroundImage
# ----------
width = event.width
height = event.height
resizedBackgroundImage = copyImage.resize((width, height))
newBackgroundImage = ImageTk.PhotoImage(resizedBackgroundImage)
label.config(image=newBackgroundImage)
# avoid garbage collection option 2
label.image = newBackgroundImage
# ----------
def createUserManualWindow(button_userManual):
global image1
userManualWindow = Toplevel(root)
def activateButtonUserManual():
button_userManual.configure(state="normal")
userManualWindow.destroy()
button_userManual.configure(state="disabled")
button_exit_userManualWindow = Button(userManualWindow, text="Exit", font=fontStyle,
command=lambda: [userManualWindow.destroy(), activateButtonUserManual()])
button_exit_userManualWindow.place(relx=0.4, rely=0.8, relwidth=0.2, relheight=0.1)
# will occurs only when esc pressed
userManualWindow.protocol("WM_DELETE_WINDOW", activateButtonUserManual)
# ----------
userManualWindow.geometry(f'{rootWidth}x{rootHeight}+{int(topLeftPosition[0])}+{int(topLeftPosition[1])}')
userManualWindow.iconbitmap('afekaImage.ico')
image1 = ImageTk.PhotoImage(Image.open('background.jpg'))
label1 = ttk.Label(userManualWindow, image=image1).pack()
label1.bind('<Configure>', adjustBackgroundImage)
label1.pack(fill=BOTH, expand=YES)
def createOverviewWindow(button_userManual):
overviewWindow = Toplevel(root)
def activateButtonOverview():
button_userManual.configure(state="normal")
overviewWindow.destroy()
button_userManual.configure(state="disabled")
button_exit_OverviewWindow = Button(overviewWindow, text="Exit", font=fontStyle,
command=lambda: [overviewWindow.destroy(), activateButtonOverview()])
button_exit_OverviewWindow.place(relx=0.4, rely=0.8, relwidth=0.2, relheight=0.1)
# will occurs only when esc pressed
overviewWindow.protocol("WM_DELETE_WINDOW", activateButtonOverview)
# ----------
overviewWindow.geometry(f'{rootWidth}x{rootHeight}+{int(topLeftPosition[0])}+{int(topLeftPosition[1])}')
overviewWindow.iconbitmap('afekaImage.ico')
# Define background image
image = Image.open('background.jpg')
copyImage = image.copy()
backgroundImage = ImageTk.PhotoImage(image)
label = ttk.Label(root, image=backgroundImage)
label.bind('<Configure>', adjustBackgroundImage)
label.pack(fill=BOTH, expand=YES)
# Configure font
fontStyle = font.Font(family="Segoe Script", size=10, weight=font.BOLD)
# Create buttons
button_userManual = Button(root, text="USER MANUAL", command=lambda: createUserManualWindow(button_userManual), font=fontStyle)
button_userManual.place(relx=0.4, rely=0.2, relwidth=0.2, relheight=0.1)
button_overview = Button(root, text="OVERVIEW", command=lambda: createOverviewWindow(button_overview), font=fontStyle)
button_overview.place(relx=0.4, rely=0.4, relwidth=0.2, relheight=0.1)
button_openDocFile = Button(root, text="DOC FILE", font=fontStyle, command=openDocFile)
button_openDocFile.place(relx=0.4, rely=0.6, relwidth=0.2, relheight=0.1)
button_quit = Button(root, text="Exit", font=fontStyle, command=root.destroy)
button_quit.place(relx=0.4, rely=0.8, relwidth=0.2, relheight=0.1)
root.mainloop()
label1 = ttk.Label(userManualWindow, image=image1).pack() should be changed to:
label1 = ttk.Label(userManualWindow, image=image1)
label1.pack()
You should call label1.pack() before placing the "Exit" button, otherwise it will overlap/hide the "Exit" button. Or call label1.lower() after label1.pack().
label is used inside adjustBackgroundImage(), so even though you bind <configure> on label1 to adjustBackgroundImage(), it would not resize image shown by label1. Use event.widget instead of label inside adjustBackgroundImage():
def adjustBackgroundImage(event):
label = event.widget
# avoid garbage collection option 1
# global resizedBackgroundImage, newBackgroundImage
# ----------
width = event.width
height = event.height
resizedBackgroundImage = copyImage.resize((width, height))
newBackgroundImage = ImageTk.PhotoImage(resizedBackgroundImage)
label.config(image=newBackgroundImage)
# avoid garbage collection option 2
label.image = newBackgroundImage
# ----------

How to get input from tkinter Entry widget on second window while the first window continues to run

from tkinter import *
def first():
root1 = Tk()
Button(root1, text = 'get Second', command= second).pack()
root1.mainloop()
def second():
root2 = Tk()
user_input = StringVar()
Entry(root2, text = user_input).pack()
Button(root2, text = 'submit', command = lambda : print(user_input.get(), '\t printed')).pack()
root2.mainloop()
first()
You are making a few basic mistakes in here -
You if want to use a second window, it should be Toplevel not root Tk window. There should be only one root window in the program. This should act as parent to all the windows.
Its a good practice in most of the cases to define the widgets like Button, Entry separately and then pack() them.
Entry should have 'textvariable' not 'text'
Following is the updated code which may help you -
from tkinter import *
root = Tk()
def first():
button = Button(root, text = 'get Second', command= second)
button.pack()
root.mainloop()
def second():
window2 = Toplevel(root)
user_input = StringVar()
entry = Entry(window2, textvariable=user_input)
entry.pack()
button = Button(window2, text = 'submit', command = lambda: print(user_input.get()))
button.pack()
first()

How to make Tkinter button open in the same windows like in many other programs

I have a program calculator, the button code opens a new window, but I want the button calculator run in the same window but not two separate, how do I instead run my code in the same windows?
P.S. the code is not mine, it is as an example
from tkinter import *
root = Tk()
root.title("Math Lab")
root.geometry("1400x1000")
heading = Label(root, text = "Welcome to the MATH Lab", font=("Berlin Sans FB", 40, "bold"), fg= "steelblue").pack()
root.configure(background= "powder blue")
def calculator():
w = Tk()
w.geometry("1400x1000")
def evaluate1():
res.configure(text="Answer: " + str(eval(entry.get())))
def evaluate(event):
res.configure(text="Answer: " + str(eval(entry.get())))
but1 = Button(w, text="Enter", width=10, height=3)
but1.place(x=650, y=100)
but1.config(command=evaluate1)
Label(w, text="Your Expression:").pack()
entry = Entry(w)
entry.bind("<Return>", evaluate)
entry.pack()
res = Label(w)
res.pack()
w.mainloop()
but1=Button(root,text="Calculator",width = 10, height = 3)
but1.place(x=100, y=100)
but1.config(command = calculator)
root.mainloop()
Any suggestions?
Here you are requesting a new window:
w = Tk()
Replace it with
w = root
and you are good to go.
(Well, you'll want to tidy up some x,y offsets, for aesthetics.)

I am having trouble making an input text box that goes through a function and outputs test to an output textbox with Tkinter

im new to Python3.6.2
So I want a program that takes an input (Via text box from tkinter) and outputs a word in my custom "language"
with this function
def Mescre(n):
Words = (n)
Mes = str.maketrans('abcdefghijklmnopqrstuvwxyz', 'ektnopzcamjqwyuxsbfdiglhrv')
print(Words.translate(Mes))
and here's what i want the window to look like
from tkinter import*
root = Tk()
Mescre = Label(root, text="Input:")
English = Label(root , text="Output:")
label1.grid(row=0, sticky=E)
label2.grid(row=1, sticky=E)
entry1 = Entry(root)
entry2 = Entry(root)
entry1.grid = (row=0, column=1)
entry2.grid = (row=1, column=1)
root.mainloop()
if "hello" was in the Input text box, i want the output to be "coqqu" in the Output text box.
See my example below:
from tkinter import *
class App:
def __init__(self, root):
self.root = root
self.sv = StringVar()
self.Mes = str.maketrans('abcdefghijklmnopqrstuvwxyz', 'ektnopzcamjqwyuxsbfdiglhrv')
self.entry = Entry(self.root, textvariable = self.sv)
self.label = Label(self.root)
self.entry.pack()
self.label.pack()
self.sv.trace("w", self.callback)
def callback(self, *args):
self.label.configure({"text": self.entry.get().translate(self.Mes)})
root = Tk()
App(root)
root.mainloop()
Here we define a StringVar() to be the value of the attribute textvariable for the Entry widget.
We then assign a callback to a trace() on the variable so that whenever the variable is updated (When someone types in the Entry) we call callback().
Within callback() we use configure() on the Label widget in order to set the text to equal the post translation version of the value of the Entry widget.
This creates a "live updating" translation effect.
Here's a basic example:
import tkinter as tk
root = tk.Tk()
def Mescre():
val = textfield.get()
Words = (val)
Mes = str.maketrans('abcdefghijklmnopqrstuvwxyz', 'ektnopzcamjqwyuxsbfdiglhrv')
print(Words.translate(Mes))
textfield = tk.Entry(root)
textfield.pack()
button = tk.Button(root, command=Mescre, text='Push')
button.pack()
root.mainloop()
Updated:
import tkinter as tk
root = tk.Tk()
def Mescre():
val = textfield.get()
Words = (val)
Mes = str.maketrans('abcdefghijklmnopqrstuvwxyz', 'ektnopzcamjqwyuxsbfdiglhrv')
translation = Words.translate(Mes)
#print(translation)
outputfield.delete(0, tk.END)
outputfield.insert(0, translation)
textfield = tk.Entry(root)
textfield.pack()
outputfield = tk.Entry(root)
outputfield.pack()
button = tk.Button(root, command=Mescre, text='Push')
button.pack()
root.mainloop()

How to add background image to my application in Tkinter?

The code picture needs to fit the screen size perfectly. I saw a bunch of tutorials but nothing seems to work.I tried adding a canvas but it covers half the screen.All my buttons go under the image itself not over it. It's getting on my nerves .
here's my code :
import tkinter as tk
import PIL
from PIL import Image, ImageTk
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
root = Tk()
w = Label(root, text="Send and receive files easily")
w.config(font=('times', 32))
w.pack()
def create_window():
window = tk.Toplevel(root)
window.geometry("400x400")
tower= PhotoImage(file="D:/icons/tower.png")
towlab=Button(root,image=tower, command=create_window)
towlab.pack()
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("Bifrost v1.0")
self.pack(fill=BOTH, expand=1)
self.img1 = PhotoImage(file="D:/icons/download.png")
self.img2 = PhotoImage(file="D:/icons/upload.png")
sendButton = Button(self, image=self.img2)
sendButton.place(x=305, y=15)
receiveButton = Button(self, image=self.img1)
receiveButton.place(x=355, y=15)
menu = Menu(self.master)
self.master.config(menu=menu)
file = Menu(menu)
file.add_command(label='Exit', command=self.client_exit)
menu.add_cascade(label='File', menu=file)
edit = Menu(menu)
edit.add_command(label='abcd')
menu.add_cascade(label='Edit', menu=edit)
help = Menu(menu)
help.add_command(label='About Us', command=self.about)
menu.add_cascade(label='Help', menu=help)
def callback():
path = filedialog.askopenfilename()
e.delete(0, END) # Remove current text in entry
e.insert(0, path) # Insert the 'path'
# print path
w = Label(root, text="File Path:")
e = Entry(root, text="")
b = Button(root, text="Browse", fg="#a1dbcd", bg="black", command=callback)
w.pack(side=TOP)
e.pack(side=TOP)
b.pack(side=TOP)
def client_exit(self):
exit()
def about(self):
top = Toplevel()
msg = Message(top, text="This is a project developed by Aditi,Sagar and
Suyash as the final year project.",
font=('', '15'))
msg.pack()
top.geometry('200x200')
button = Button(top, text="Okay", command=top.destroy)
button.pack()
top.mainloop()
root.resizable(0,0)
#size of the window
root.geometry("700x400")
app = Window(root)
root.mainloop()
Overlaying elements is tricky. I think this might be approximately what you're looking for. At least it's a start...
import PIL
from PIL import Image, ImageTk
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
root = Tk()
class Window:
def __init__(self, master=None):
tower = PIL.Image.open("Images/island.png")
master.update()
win_width = int(master.winfo_width())
win_height = int(master.winfo_height())
# Resize the image to the constraints of the root window.
tower = tower.resize((win_width, win_height))
tower_tk = ImageTk.PhotoImage(tower)
# Create a label to hold the background image.
canvas = Canvas(master, width=win_width, height=win_height)
canvas.place(x=0, y=0, anchor='nw')
canvas.create_image(0, 0, image=tower_tk, anchor='nw')
canvas.image = tower_tk
frame = Frame(master)
frame.place(x=win_width, y=win_height, anchor='se')
master.update()
w = Label(master, text="Send and receive files easily", anchor='w')
w.config(font=('times', 32))
w.place(x=0, y=0, anchor='nw')
master.title("Bifrost v1.0")
self.img1 = PhotoImage(file="Images/logo.png")
self.img2 = PhotoImage(file="Images/magnifier.png")
frame.grid_columnconfigure(0, weight=1)
sendButton = Button(frame, image=self.img2)
sendButton.grid(row=0, column=1)
sendButton.image = self.img2
receiveButton = Button(frame, image=self.img1)
receiveButton.grid(row=0, column=2)
receiveButton.image = self.img1
menu = Menu(master)
master.config(menu=menu)
file = Menu(menu)
file.add_command(label='Exit', command=self.client_exit)
menu.add_cascade(label='File', menu=file)
edit = Menu(menu)
edit.add_command(label='abcd')
menu.add_cascade(label='Edit', menu=edit)
help = Menu(menu)
help.add_command(label='About Us', command=self.about)
menu.add_cascade(label='Help', menu=help)
def callback():
path = filedialog.askopenfilename()
e.delete(0, END) # Remove current text in entry
e.insert(0, path) # Insert the 'path'
# print path
w = Label(root, text="File Path:")
e = Entry(root, text="")
b = Button(root, text="Browse", fg="#a1dbcd", bg="black", command=callback)
w.pack(side=TOP)
e.pack(side=TOP)
b.pack(side=TOP)
def client_exit(self):
exit()
def about(self):
message = "This is a project developed by Aditi,Sagar and"
message += "Suyash as the final year project."
messagebox.showinfo("Delete Theme", message)
root.resizable(0,0)
#size of the window
root.geometry("700x400")
app = Window(root)
root.mainloop()

Resources