How to make find and replace system in python - python

This a simple code in which i have created a text area using tkinter and a menu in which there is a option of find and replace in which if user click on it then a gui will appear in which user will enter a word to whom they want to replace and then a word to whom they want replace with but till now i have just created a gui . But how can i replace word with a word given by user with the text of text area that i have created.
from tkinter import *
import tkinter.font as font
from tkinter import messagebox
root = Tk()
root.title("MyCodeEditor")
editor = Text()
editor.pack()
menu_bar = Menu(root)
def find_replace():
f = Tk()
f.title("Find and Replace")
find_label = Label(f,text = "Find : ")
replace_label = Label(f,text = "Replace : ")
find_label.grid(row = 0 , column = 0)
replace_label.grid(row = 3 , column = 0)
global find_enter
global replace_enter
find_enter = Entry(f,fg = "black" , background = "blue",borderwidth = 5,width = 40)
replace_enter = Entry(f,fg = "black" , background = "blue", borderwidth = 5, width =40 )
find_enter.grid(row = 0 , column = 1)
replace_enter.grid(row = 3 , column = 1)
btn_replace = Button(f,text = 'Replace',fg = 'black',command = None)
btn_replace.grid(row=0, column = 5)
format_bar = Menu(menu_bar , tearoff = 0)
format_bar.add_command(label = 'Find and Replace',command = find_replace)
menu_bar.add_cascade(label = 'Format' ,menu = format_bar )
root.config(menu = menu_bar)
root.mainloop()

Here is a simple example (most of it is just the GUI looks, the main part is the actual replace method):
from tkinter import Tk, Text, Entry, Frame, Button, Toplevel, Label, Menu, TclError, IntVar
normal_font = ('comicsans', 10)
class FindAndReplace(Toplevel):
def __init__(self, parent, text_widget: Text):
Toplevel.__init__(self, parent)
self.focus_force()
self.title('Find and Replace')
self.geometry('500x200')
self.resizable(False, False)
self.parent = parent
self.widget = text_widget
try:
self.start_index = self.widget.index('sel.first')
self.end_index = self.widget.index('sel.last')
except TclError:
self.start_index = '1.0'
self.end_index = 'end'
self.to_find = None
self.to_replace = None
# creating find entry
find_frame = Frame(self)
find_frame.pack(expand=True, fill='both', padx=20)
Label(find_frame, text='Find:', font=normal_font).pack(side='left', fill='both', padx=20)
self.find_entry = Entry(find_frame)
self.find_entry.pack(side='right', expand=True, fill='x')
# creating replace entry
replace_frame = Frame(self)
replace_frame.pack(expand=True, fill='both', padx=20)
Label(replace_frame, text='Replace:', font=normal_font).pack(side='left', fill='both', padx=20)
self.replace_entry = Entry(replace_frame)
self.replace_entry.pack(side='right', expand=True, fill='x')
# creating buttons
button_frame = Frame(self)
button_frame.pack(expand=True, fill='both', padx=20)
Button(button_frame, text='Cancel', font=normal_font,
command=self.destroy).pack(side='right', fill='x', padx=5)
Button(button_frame, text='Replace', font=normal_font,
command=self.replace).pack(side='right', fill='x', padx=5)
def __find_get(self):
self.to_find = self.find_entry.get()
def __replace_get(self):
self.to_replace = self.replace_entry.get()
def replace(self):
self.__find_get()
self.__replace_get()
if not self.to_replace:
return
length = IntVar()
index = self.widget.search(self.to_find, self.start_index, stopindex=self.end_index, count=length)
end_index = self.widget.index(index + f'+{length.get()}c')
self.widget.delete(index, end_index)
self.widget.insert(index, self.to_replace)
root = Tk()
menu_bar = Menu(root)
file_menu = Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label='File', menu=file_menu)
file_menu.add_command(label='Find and Replace', command=lambda: FindAndReplace(root, text))
root.config(menu=menu_bar)
text = Text(root)
text.pack()
root.mainloop()
Obviously some other functionality could be added such as replace all

Related

Python GUI App is not functioning well, help me fix it?

Here's my code of a gui app using tkinter library, it creats tables and prints orders for each table and gives the ability to edit orders on every table. the goal of it to know what did each table order. but editing the orders doesn't seem to work at all, I need help fixing it.
import tkinter as tk
class TableOrdersApp:
def __init__(self, master):
self.tables = []
self.table_list = tk.Listbox(master)
self.table_list.pack(side=tk.LEFT, fill=tk.BOTH)
self.table_list.bind("<<ListboxSelect>>", self.refresh_label)
self.orders_label = tk.Label(master, text="", anchor=tk.W, justify=tk.LEFT, wraplength=400)
self.orders_label.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.button_frame = tk.Frame(master)
self.button_frame.pack(side=tk.RIGHT)
self.add_button = tk.Button(self.button_frame, text="Add Table", command=self.add_table)
self.add_button.pack(side=tk.TOP)
self.remove_button = tk.Button(self.button_frame, text="Remove Table", command=self.remove_table)
self.remove_button.pack(side=tk.TOP)
self.edit_button = tk.Button(self.button_frame, text="Edit Order", command=self.edit_order)
self.edit_button.pack(side=tk.TOP)
self.remove_order_button = tk.Button(self.button_frame, text="Remove Order", command=self.remove_order)
self.remove_order_button.pack(side=tk.TOP)
def add_table(self):
self.tables.append([])
self.table_list.insert(tk.END, "Table {}".format(len(self.tables)))
def remove_table(self):
index = self.table_list.curselection()[0]
self.tables.pop(index)
self.table_list.delete(index)
def refresh_label(self, event=None):
self.orders_label.config(text="\n".join(self.tables[self.table_list.curselection()[0]]))
def edit_order(self):
index = self.table_list.curselection()[0]
orders = self.tables[index]
if self.orders_label.select_present():
start_index = self.orders_label.index(tk.SEL_FIRST)
end_index = self.orders_label.index(tk.SEL_LAST)
selected_text = self.orders_label.selection_get()
num_newlines = selected_text.count("\n")
order_index = start_index.split(".")[0] - 1 - num_newlines
new_order = tk.simpledialog.askstring("Edit Order", "Enter the new order:")
orders[order_index] = new_order
self.refresh_label()
def remove_order(self):
index = self.table_list.curselection()[0]
orders = self.tables[index]
start_index = self.orders_label.index(tk.SEL_FIRST)
end_index = self.orders_label.index(tk.SEL_LAST)
num_newlines = self.orders_label.get(start_index, end_index).count("\n")
order_index = start_index.split(".")[0] - 1 - num_newlines
orders.pop(order_index)
self.refresh_label()
# Create the main window
root = tk.Tk()
# Create an instance of the TableOrdersApp class
app = TableOrdersApp(root)
# Run the main loop of the app
root.mainloop()
I tried to make it print a label and make it editable using "edit order" button, but the button itself doesn't seem to work, and I want it to print "Empty" if the table has no orders how can i do that.
Look in edit_order and remove_order function. Must easier to write less coding.
Here is code:
import tkinter as tk
class TableOrdersApp:
def __init__(self, master):
self.tables = []
self.table_list = tk.Listbox(master)
self.table_list.pack(side=tk.LEFT, fill=tk.BOTH)
self.table_list.bind("<<ListboxSelect>>", self.refresh_label)
self.orders_label = tk.Label(master, text="", anchor=tk.W, justify=tk.LEFT, wraplength=400)
self.orders_label.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.button_frame = tk.Frame(master)
self.button_frame.pack(side=tk.RIGHT)
self.add_button = tk.Button(self.button_frame, text="Add Table", command=self.add_table)
self.add_button.pack(side=tk.TOP)
self.remove_button = tk.Button(self.button_frame, text="Remove Table", command=self.remove_table)
self.remove_button.pack(side=tk.TOP)
self.edit_button = tk.Button(self.button_frame, text="Edit Order", command=self.edit_order)
self.edit_button.pack(side=tk.TOP)
self.remove_order_button = tk.Button(self.button_frame, text="Remove Order", command=self.remove_order)
self.remove_order_button.pack(side=tk.TOP)
def add_table(self):
self.tables.append([])
self.table_list.insert(tk.END, "Table {}".format(len(self.tables)))
def remove_table(self):
index = self.table_list.curselection()[0]
self.tables.pop(index)
self.table_list.delete(index)
def refresh_label(self, event=None):
self.orders_label.config(text="\n".join(self.tables[self.table_list.curselection()[0]]))
def edit_order(self):
index = self.table_list.curselection()[0]
orders = self.table_list.get(index)
print(index)
order = orders
self.orders_label.configure(text=order)
#if self.orders_label.select_present():
#start_index = self.orders_label.index(tk.SEL_FIRST)
#end_index = self.orders_label.index(tk.SEL_LAST)
#selected_text = self.orders_label.selection_get()
#num_newlines = selected_text.count("\n")
#order_index = start_index.split(".")[0] - 1 - num_newlines
#new_order = tk.simpledialog.askstring("Edit Order", "Enter the new order:")
#orders[order_index] = new_order
#self.refresh_label()
def remove_order(self):
remove_orders = self.table_list.curselection()
self.table_list.delete(remove_orders)
self.orders_label.configure(text="")
#index = self.table_list.curselection()[0]
#orders = self.tables[index]
#start_index = self.orders_label.index(tk.SEL_FIRST)
#end_index = self.orders_label.index(tk.SEL_LAST)
#num_newlines = self.orders_label.get(start_index, end_index).count("\n")
#order_index = start_index.split(".")[0] - 1 - num_newlines
#orders.pop(order_index)
#self.refresh_label()
# Create the main window
root = tk.Tk()
# Create an instance of the TableOrdersApp class
app = TableOrdersApp(root)
# Run the main loop of the app
root.mainloop()
Result when executes:
Result when selected:
Result when removed order:

Python tkinter Radio Buttons "On Submit"

in my code I do not understand how radio buttons are working. My problem is, that the radio-buttons variables are not passed further.
from tkinter import *
class SimpleDialog(Frame):
def __init__(self):
super().__init__()
self.output1 = ""
self.output10 = ""
self.output11 = ""
self.output12 = ""
self.initUI()
def initUI(self):
self.master.title("New Input")
self.pack(fill=BOTH, expand=True)
frame1 = Frame(self)
frame1.pack(fill=X)
lbl1 = Label(frame1, text="Name:", width=20)
lbl1.pack(side=LEFT, padx=5, pady=10)
self.entry1 = Entry(frame1, textvariable=self.output1)
self.entry1.insert(0,"Your name")
self.entry1.pack(fill=X, padx=5, expand=True)
auswahl = IntVar()
auswahl.set(0)
frame10 = Frame(self)
frame10.pack(fill=X)
lbl10 = Label(frame10, text="Do you like tomatoes?", width=40)
lbl10.pack(side=LEFT, padx=5, pady=5)
self.entry10 = Radiobutton(frame10, text="No",variable=auswahl, padx = 0, value=0).pack(anchor=W)
self.entry11 = Radiobutton(frame10, text="Sometimes",variable=auswahl,padx = 0, value=1).pack(anchor=W)
self.entry12 = Radiobutton(frame10, text="Yes",variable=auswahl,padx = 0, value=2).pack(anchor=W)
frame3 = Frame(self)
frame3.pack(fill=X)
print(self.entry12)
btn = Button(frame3, text="New entry", command=self.onSubmit)
btn.pack(padx=5, pady=10)
def onSubmit(self):
# Input
self.output1 = self.entry1.get()
# Radio-Buttons
self.output10 = self.entry10
self.output11 = self.entry11
self.output12 = self.entry12
self.quit()
def main():
# This part triggers the dialog
root = Tk()
root.geometry("650x300+500+300")
app = SimpleDialog()
root.mainloop()
# Here we can act on the form components or
# better yet, copy the output to a new variable
user_input = (app.output1, app.output10, app.output11, app.output12)
try:
root.destroy()
except:
pass
return user_input
if __name__ == '__main__':
diaginput = main()
Can you help me to change the code, so that I can get the values of the radio buttons, e.g. print(diaginput).
I have problems to get the values of the radio buttons.
You should not try to access the radiobuttons but the variable you used to store the values.
But you should make the variable an attribute of the class of your dialog to access it from all methods:
self.auswahl = IntVar()
self.auswahl.set(0)
self.entry10 = Radiobutton(frame10, text="No",variable=self.auswahl, padx = 0, value=0).pack(anchor=W)
self.entry11 = Radiobutton(frame10, text="Sometimes",variable=self.auswahl,padx = 0, value=1).pack(anchor=W)
self.entry12 = Radiobutton(frame10, text="Yes",variable=self.auswahl,padx = 0, value=2).pack(anchor=W)
In the function on submit, you may then just get the value of the .auswahl attribute
# Radio-Buttons
self.output = self.auswahl.get()
The variable self.output will then hold an integer with a value between 0 and 2, depending on your selection.

Tkinter: How to insert text into text widget that's part of a Frame?

I need help inserting text in a Text widget that's part of a Frame.
class Test_frame(Frame):
def __init__(self):
Frame.__init__(self)
self.config(width = 700, height = 450)
self.logs_frame = LabelFrame(self, height = 402, width = 348, text = 'Logs')
self.logs_frame.grid(column = 1, row = 0, pady=10, sticky = N)
self.logs_frame.grid_propagate(0)
self.text_box = Text(self.logs_frame, width=40, pady=10, height=22)
self.text_box.pack(side="left")
self.scroll_y = Scrollbar(self.logs_frame, orient="vertical", command=self.text_box.yview)
self.scroll_y.pack(side="left", expand=True, fill="y")
self.text_box.configure(yscrollcommand=self.scroll_y.set)
self.text_box.insert (?????.END, "Sample Text")
I have no idea how to access that Text widget now.
Test_frame is part of a Notebook:
class App(Tk):
def __init__(self):
Tk.__init__(self)
self.my_notebook = ttk.Notebook(self)
self.my_notebook.pack(pady = 5)
self.frames = {}
for F in (Test_frame, Final_flash_frame):
frame = F()
self.frames[F] = frame
frame.pack(fill = 'both', expand = 1)
self.my_notebook.add(self.frames[Test_frame], text = "Testing")
I created a minimal source, but I guess you solved your problem.
I added a little button to add text, and added some text from outside the class.
Here it is, anyway:
import tkinter as Tk
import tkinter.ttk as ttk
from tkinter import *
def BumpText(textbox):
textbox.insert(END,", MORE TEXT")
class Test_frame(Frame):
def __init__(self):
Frame.__init__(self)
self.config(width = 700, height = 450)
self.logs_frame = LabelFrame(self, height = 402, width = 348, text = 'Logs')
self.logs_frame.grid(column = 1, row = 0, pady=10, sticky = N)
self.logs_frame.grid_propagate(0)
self.text_box = Text(self.logs_frame, width=40, pady=10, height=22)
self.text_box.pack(side="left")
self.scroll_y = Scrollbar(self.logs_frame, orient="vertical", command=self.text_box.yview)
self.scroll_y.pack(side="left", expand=True, fill="y")
self.text_box.configure(yscrollcommand=self.scroll_y.set)
self.text_box.insert(END, "Sample Text")
self.button = Button(self.logs_frame, text="Add\nText", command=lambda:self.text_box.insert(END, ", More Text"))
self.button.pack(side="bottom")
class App(Tk):
def __init__(self):
Tk.__init__(self)
self.my_notebook = ttk.Notebook(self)
self.my_notebook.pack(pady = 5)
self.frames = {}
for F in (Test_frame,): # , Final_flash_frame):
frame = F()
self.frames[F] = frame
frame.pack(fill = 'both', expand = 1)
self.my_notebook.add(self.frames[Test_frame], text = "Testing")
for F,f in self.frames.items():
try:
f.text_box.insert(END," (Added by App)")
except Exception as e:
pass # ignore frames without text_box
if __name__ == "__main__":
App().mainloop()
Ok, so apparently just using:
self.text_box.insert (END, "Sample Text")
works
Cheers,
A

How to replace an existing image instead of adding additional images?

This is my first time here, and I would really appreciate some help with this.
So I have some code which runs a Tkinter tab and shows 2 buttons. If you click the first one, a picture of a cat appears.
However, if you click the button again, the same picture appears again at the bottom, making there 2.
If I click the other button, titled N/A, a different picture appears. But if you click the button again, the picture duplicates.
I want to make it so that when each button is pressed, the image is replaced, not duplicated.
Here is what I have so far.
from tkinter import *
root = Tk()
class HomeClass(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.WelcomeLabel = Label(root, text="Welcome to the game!",
bg="Black", fg="White")
self.WelcomeLabel.pack(fill=X)
self.FirstButton = Button(root, text="Start", bg="RED", fg="White",
command=self.FirstClick)
self.FirstButton.pack(side=LEFT, fill=X)
self.SecondButton = Button(root, text="N/A", bg="Blue", fg="White",
command=self.SecondClick)
self.SecondButton.pack(side=LEFT, fill=X)
def FirstClick(self):
FirstPhoto = PhotoImage(file="keyboardcat.gif")
FiLabel = Label(root, image=FirstPhoto)
FiLabel.img = FirstPhoto
FiLabel.pack()
def SecondClick(self):
FirstPhoto = PhotoImage(file="donald.gif")
FiLabel = Label(root, image=FirstPhoto)
FiLabel.img = FirstPhoto
FiLabel.pack()
k = HomeClass(root)
root.mainloop()
That's becouse every time you click a button, you're calling FirstClick method which in turn creates new instance of PhotoImage class. I think it would be better to store FirstPhoto and in every FirstClick method call check if it is already has value or not.
class HomeClass(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.WelcomeLabel = Label(root, text="Welcome to the game!",
bg="Black", fg="White")
self.WelcomeLabel.pack(fill=X)
self.FirstButton = Button(root, text="Start", bg="RED", fg="White",
command=self.FirstClick)
self.FirstButton.pack(side=LEFT, fill=X)
self.SecondButton = Button(root, text="N/A", bg="Blue", fg="White",
command=self.SecondClick)
self.SecondButton.pack(side=LEFT, fill=X)
self.FirstPhoto = None
def FirstClick(self):
if self.FirstPhoto is None:
self.FirstPhoto = PhotoImage(file="ksiazka.png")
self.FiLabel = Label(root, image=self.FirstPhoto)
self.FiLabel.img = self.FirstPhoto
self.FiLabel.pack()
Try this to change SecondPhoto
def SecondClick(self):
if self.SecondPhoto is None:
self.SecondPhoto = PhotoImage(file="ksiazka.png")
self.SecondPhotoLabel = Label(root, image=self.FirstPhoto)
self.SecondPhotoLabel.img = self.SecondPhoto
self.SecondPhotoLabel.pack()
Else:
self.SecondPhotoLabel.config(image='newimage')
self.SecondPhotoLabel.update()
Note - you can declare the newImage before as you have to read it with PhotoImage and then just put the image name in the .config
In this example you have two methods FirstClick, SecondClick to display an image and two methods to clear an first and second image accordingly: clearFirstImage, clearSecondImage. You just have to add two buttons to trigger those clear methods :)
from tkinter import *
from tkFileDialog import askopenfilename
root = Tk()
class HomeClass(object):
def __init__(self, master):
self.master = master
self.frame = Frame(master)
self.WelcomeLabel = Label(root, text="Welcome to the game!",
bg="Black", fg="White")
self.WelcomeLabel.pack(fill=X)
self.FirstButton = Button(root, text="Start", bg="RED", fg="White",
command=self.FirstClick)
self.FirstButton.pack(side=LEFT, fill=X)
self.SecondButton = Button(root, text="N/A", bg="Blue", fg="White",
command=self.SecondClick)
self.SecondButton.pack(side=LEFT, fill=X)
self.ToggleButtonText = "Show image"
self.ToggleButton = Button(root, text=self.ToggleButtonText, bg="Grey", fg="White",
command=self.ToggleClick)
self.ToggleButton.pack(side=LEFT, fill=X)
self.FirstPhoto = None
self.FiLabel = None
self.SecondPhoto = None
self.SecondPhotoLabel = None
self.ToggleButtonPhoto = None
self.ToggleButtonPhotoLabel = None
self.frame.pack()
def FirstClick(self):
if self.FirstPhoto is None:
self.FirstPhoto = PhotoImage(file="ksiazka.png")
self.FiLabel = Label(root, image=self.FirstPhoto)
self.FiLabel.img = self.FirstPhoto
self.FiLabel.pack()
def ToggleClick(self):
if self.ToggleButtonPhoto is None:
self.ToggleButtonPhoto = PhotoImage(file="ksiazka.png")
self.ToggleButtonPhotoLabel = Label(self.frame, image=self.ToggleButtonPhoto)
self.ToggleButtonPhotoLabel.img = self.ToggleButtonPhoto
self.ToggleButtonPhotoLabel.pack()
# and set label
self.ToggleButton.config(text="Hide image")
else:
self.ToggleButton.config(text="Show image")
self.ToggleButtonPhotoLabel.destroy()
self.ToggleButtonPhotoLabel.img = None
self.ToggleButtonPhotoLabel = None
self.ToggleButtonPhoto = None
self.frame.pack()
def SecondClick(self):
filename = askopenfilename()
allowed_extensions = ['jpg', 'png']
if len(filename) > 0 and filename.split('.')[-1] in allowed_extensions:
self.SecondPhoto = PhotoImage(file=filename)
self.SecondPhotoLabel = Label(root, image=self.SecondPhoto)
self.SecondPhotoLabel.img = self.SecondPhoto
self.SecondPhotoLabel.pack()
def clearFirstImage(self):
self.FirstPhoto = None
self.FiLabel = None
def clearSecondImage(self):
self.SecondPhoto = None
self.SecondPhotoLabel = None
k = HomeClass(root)
root.mainloop()
If you want to replace an existing image, first create the label the image is displayed in, and simply reconfigure only its image option with each click. Below is an example that does that:
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 download_images():
# In order to fetch the image online
try:
import urllib.request as url
except ImportError:
import urllib as url
url.urlretrieve("https://i.stack.imgur.com/57uJJ.gif", "13.gif")
url.urlretrieve("https://i.stack.imgur.com/8LThi.gif", "8.gif")
class ImageFrame(tk.Frame):
def __init__(self, master, *args, **kwargs):
tk.Frame.__init__(self, master, *args, **kwargs)
self._create_widgets()
self._display_widgets()
def _create_widgets(self):
def __create_image_label():
def ___load_images():
self.label.images = list()
self.label.images.append(tk.PhotoImage(file="8.gif"))
self.label.images.append(tk.PhotoImage(file="13.gif"))
self.label = tk.Label(self)
___load_images()
def __create_buttons():
self.buttons = list()
for i in range(2):
self.buttons.append(tk.Button(self, text=i,
command=lambda i=i: self.replace_image(i)))
__create_image_label()
__create_buttons()
def replace_image(self, button_index):
"""
Replaces the image in label attribute based on the index of the
button pressed.
"""
self.label['image'] = self.label.images[button_index]
def _display_widgets(self):
self.label.pack()
for i in range(2):
self.buttons[i].pack(fill='x', expand=True)
if __name__ == '__main__':
#download_images() # comment out after initial run
root = tk.Tk()
frame = ImageFrame(root)
frame.pack()
tk.mainloop()

How to open a new frame from a current window in python tkinter?

class Login:
def __init__(self):
Label1 = Label(root,text = "Username")
Label2 = Label(root,text = "Password")
self.Entry1 = Entry(root)
self.Entry2 = Entry(root,show = "*")
Label1.grid(row=0)
Label2.grid(row=1)
self.Entry1.grid(row = 0,column = 1)
self.Entry2.grid(row = 1,column = 1)
root.minsize(width = 300,height = 80)
##new_window_button = Button(text="new window", command = ????)
##new_window_button.grid(columnspan = 2)
lgbutton = Button(text = "Login",command = self.ButtonClicked)
lgbutton.grid(columnspan = 2)
def ButtonClicked(self):
username = self.Entry1.get()
password = self.Entry2.get()
GetDatabase(username,password)
Currently this is what I have to create a window, however I want it to that when the new_window_button is clicked, the new page has its own widgets. I've used Toplevel before but it creates a child window without the widgets. Instead, the widgets are added to the parent window.
Judging by the comments it looks as though you are struggling with declaring the correct parent for widgets.
When a widget is declared the first parameter passed in to it is it's parent. For example:
Label(root, text="I'm in the root window.")
# ^ This is the parent
As opposed to:
Label(top, text="I'm in the top window.")
# ^ This is the parent
Please see a more fleshed out example below:
from tkinter import *
root = Tk()
top = Toplevel(root)
label1 = Label(root, text="I'm a placeholder in your root window.")
label2 = Label(top, text="I'm a placeholder in your top window.")
label1.pack()
label2.pack()
root.mainloop()
import tkinter
from tkinter import *
class LoginForm(Frame):
def __init__(self,master=None):
super().__init__(master)
self.pack()
self.createWidget()
def createWidget(self):
self.lblEmailId=Label(self,text="Email Id")
self.lblEmailId.grid(row=0,column=0)
self.varEmailid=StringVar()
self.txtEmailId=Entry(self,textvariable=self.varEmailid)
self.txtEmailId.grid(row=0,column=1)
self.txtEmailId.bind("<KeyRelease>",self.key_press)
self.lblPassword = Label(self, text="Password")
self.lblPassword.grid(row=1, column=0)
self.varPassword=StringVar()
self.txtPassword= Entry(self, textvariable=self.varPassword)
self.txtPassword.grid(row=1, column=1)
self.btnLogin=Button(self,text="Login")
self.btnLogin.grid(row=2,column=1)
self.btnLogin.bind("<Button-1>",self.btnLogin_click)
def btnLogin_click(self,event):
self.varPassword.set(self.varEmailid.get())
LoginWindow=Toplevel()
def key_press(self,event):
self.varPassword.set(self.varEmailid.get())
root=Tk()
fromLogin=LoginForm(root)
root.mainloop()

Categories