How to know which button is pressed in tkinter? [duplicate] - python

This question already has answers here:
tkinter creating buttons in for loop passing command arguments
(3 answers)
Closed last year.
from tkinter import *
from Createwindow import *
button_name = ""
def click():
window = Tk()
window.geometry("600x500")
frame = Frame(window, bg = "#161853", width = 600, height = 500)
row_ = 0
column_ = 0
list = []
with open ("Passwords.txt", 'r') as data_file:
data = data_file.readlines()
for i in data:
names = i.split("|")
list.append(names[0])
for i in range(len(list)):
name = list[i]
button_ = Button(frame,text=name, font=("Helvetica", 12), width=16, bg="white", fg="black", command=create_window)
button_.grid(row=row_, column=column_, padx=(25, 0), pady=(25,0))
column_ += 1
if column_ == 3:
row_ += 1
column_ = 0
button_name = button_.cget('text')
frame.pack(fill="both", expand=True)
window.mainloop()
def create_window():
def fill_fields():
with open ("Passwords.txt", 'r') as data_file:
data = data_file.readlines()
for i in data:
names = i.split("|")
if names[0] == button_name:
Website_.insert(0, names[0])
Username_.insert(0, names[1])
Password_.insert(0, names[2])
def save_password():
if Website_.get() == "" or Username_.get() == "" or Password_.get() == "":
window = Tk()
Error_Message = Label(window, text = "Error! Please fill all the above fields.", bg="red", fg="white", font=("Arial", 16))
Error_Message.pack()
window.mainloop()
else:
with open("Passwords.txt" , 'a') as file:
file.write(Website_.get() + "|" + Username_.get() + "|" + Password_.get() + "\n")
window = Tk()
window.geometry("600x500")
window.configure(bg="#161853")
window.minsize(600, 500)
frame = Frame(window, bg="#161853")
frame.rowconfigure(2, weight=1)
frame.columnconfigure([0, 1, 2], weight=1)
Text = Label(frame, text="Save your password here", font=("Helvetica", 14), fg="white", bg="#161853")
Text.grid(row=0, column=1, pady=(0,25))
Website = Label(frame, text="Website:", font=("Helvetica", 14), fg="white", bg="#161853")
Website.grid(row=1, column=0, padx=(0, 15), pady=(0,20))
Website_ = Entry(frame, width=25)
Website_.grid(row=1, column=1, pady=(0, 20))
Username = Label(frame, text="Username/Email:", font=("Helvetica", 14), fg="white", bg="#161853")
Username.grid(row=2, column=0, padx=(0, 15), pady=(0, 20))
Username_ = Entry(frame, width=25)
Username_.grid(row=2, column=1, pady=(0, 20))
Password = Label(frame, text="Password:", font=("Helvetica", 14), fg="white", bg="#161853" )
Password.grid(row=3, column=0, padx=(0, 15), sticky="s")
Password_ = Entry(frame, width=25)
Password_.grid(row=3, column=1, pady=(0, 30), sticky="s")
Generate = Button(frame, text="Generate Password", font=("Helvetica", 12), width=16)
Generate.grid(row=3, column=2, sticky="s")
Save = Button(frame, text="Save Password", font=("Helvetica", 12), width=14, command=save_password)
Save.grid(row=4, column=1)
frame.place(relx=0.5, rely=0.5, anchor="center")
fill_fields()
window.mainloop()
In this piece of code basically I am creating a window where all the passwords saved in password.txt file will appear.
The code creates a button on the name of the website whose password is saved.
What I want to do is that when that button is clicked I want to get the text of the clicked button bcoz all the buttons are created automatically they have same name and the text of button is the one that is created in the last iteration.

You may pass the argument while adding click event in dynamic generated button.
for example below is your old code:
button_ = Button(frame,text = name , font = ("Helvetica", 12), width = 16, bg = "white" , fg = "black", command= create_window)
If you want to get the value of name when click on this button. Just do as like below:
button_ = Button(frame,text = name , font = ("Helvetica", 12), width = 16, bg = "white" , fg = "black", command= create_window(name))
Here i'm adding name argument in create_window function.
That i had already impletemented in my project and its working fine. Please try it and let me know if you will face any issue.
Please check below link for more details.
https://www.delftstack.com/howto/python-tkinter/how-to-pass-arguments-to-tkinter-button-command/

Related

How to rewrite entry in Python Tkinter

I have a problem where to callbacks adding text to Entry without cleaning it and without overwriting:
This two fuction is callback in button in tkinter, and when you using it - if adding on front. IDK why
All code here: https://pastebin.com/88E9EU57
def encryptString(text,key,num):
text = normalizeText(text)
text = caesarify(text,key)
text = groupify(text, num)
data = str(text)
resultFrame1 = tkinter.Frame(master=root, relief="flat", padx=3, pady=3, width=100, bg="LightSteelBlue4")
title1 =tkinter.Label(master=resultFrame1,text="Your encrypted text:",
fg="gray5", font=("Helvetica ", 25), height=1, bg="LightSteelBlue4")
title1.pack()
resultOutput1 = tkinter.Entry(master=resultFrame1, text="encrypted text here:", fg="gray13",
width=100, font=("Helvetica", 12), relief="flat", bd=2, bg="LightSteelBlue1")
resultOutput1.insert(0, data)
resultOutput1.pack(padx = 5, pady = 5)
resultFrame1.pack()
def decryptString(text,key):
text = ungroupify(text)
text = caesarify(text,key)
data2 = str(text)
resultFrame2 = tkinter.Frame(master=root, relief="flat", padx=3, pady=3, width=100, bg="LightSteelBlue4")
title2 =tkinter.Label(master=resultFrame2,text="Your decrypted text:",
fg="gray5", font=("Helvetica ", 25), height=1, bg="LightSteelBlue4")
title2.pack()
resultOutput2 = tkinter.Entry(master=resultFrame2, text="encrypted text here:", fg="gray13",
width=100, font=("Helvetica", 12), relief="flat", bd=2, bg="LightSteelBlue1")
resultOutput2.insert(0, data2)
resultOutput2.pack(padx = 5, pady = 5)
resultFrame2.pack()

Parameters passed to a function does not works as intended

When the "view" button is pressed, it should trigger the function solution(i) such that label should be displayed in the new window. The problem is that the window opens and the previous label is packed but the label which gets it's text from "i" does not gets packed, Is there any issue in passing the parameter.
Any help is appreciated.
root = Tk()
root.config(background = "#303939")
root.state('zoomed')
def pre():
with open("DoubtSolution.txt","r+") as f:
dousol = f.read()
dousol_lst = dousol.split("`")
k = 0
window = Tk()
window.config(background = "#303939")
window.state('zoomed')
predoubt = Label(window,
text="Previous Doubts",
fg="Cyan",
bg="#303939",
font="Helvetica 50 bold"
).grid(row=0, column=1)
def solution(text):
print(text)
window1 = Tk()
window1.config(background="#303939")
window1.state('zoomed')
sol = Label(window1,
text=text[:text.find("~")],
font=font.Font(size=20),
bg="#303939",
fg="Cyan")
sol.pack()
window1.mainloop()
for i in dousol_lst:
if i[-5:] == admno:
doubt = Label(window, text=i[i.find("]]")+2:i.find("}}}}")], font=font.Font(size=20), bg="#303939",
fg="Cyan")
doubt.grid(row=2+k, column=1, pady=10)
view = Button(
master=window,
text="View", font=font.Font(size=15, family="Helvetica"),
activebackground="White",
bg="Teal",
bd=0.8,
fg="White",
command = lambda k = k:solution(i)
)
view.grid(row=2+k, column=2, padx=20)
k=k+1
window.mainloop()
previous = Button(
master=root,
text="Previous Doubts", font="Helvetica 22 bold",
activebackground="White",
bg="Teal",
bd=0.8,
fg="White",
command = pre
).grid(row=4, column=3, padx=20)
root.mainloop()

Python: How can I remove excel entries via openpyxl using a feedback loop?

I am building a small app to study the vocabulary of various languages (see below the code for Mandarin). I have the basic funcions which work well. Now I want to add a button in my GUI where i can remove entries (i.e. individual words) from the database, once i have mastered the word (i.e. a button in tkinter which would remove the entry). After removing, the random function in python should then only select words from the reduced database. Do you have any idea how to do this? Any help is welcome!
from tkinter import *
import random
import sys
import os
randvalue_start = random.randint(2, 592)
window = Tk()
window.title('Mandarin Vocabulary')
window.geometry('500x400')
icon = PhotoImage(file = r'C:\Users\PycharmProjects\Mandarin\HSKlogopng.600px.png')
icon2 = icon.subsample(5 ,5)
label1 = Label(window, image = icon2, anchor="ne")
import openpyxl
path = r"\Users\PycharmProjects\Mandarin\characters.xlsx"
worbook = openpyxl.load_workbook(path, read_only=True)
sheet = worbook.active
row_count = (sheet.max_row)
def english_btn1():
global randvalue_start
english = f"B{randvalue_start}"
english_value = sheet[english].value
label_eng = Label(window, text=english_value+":", width=20, height=3, font=("TkDefaultFont",15))
label_pin = Label(window, text="", font=30, width=15, height=3)
label_mand = Label(window, text="", font=30, width=15, height=4)
label_eng.grid(row=8,column=1,rowspan=2)
label_pin.grid(row=8, column=2)
label_mand.grid(row=9, column=2)
def pinying_btn2():
global randvalue_start
pinying = f"C{randvalue_start}"
mandarin = f"D{randvalue_start}"
pinying_value = sheet[pinying].value
mandarin_value = sheet[mandarin].value
combined = f"{pinying}'/'{mandarin}"
combined_value = f"{pinying_value}'/'{mandarin_value}"
label_pin = Label(window ,text=pinying_value,font=("TkDefaultFont",15), width=10, height=2)
label_mand = Label(window,text=mandarin_value,font=("TkDefaultFont",30), width=8,height=2, borderwidth=5,relief="ridge")
label_pin.grid(row=8,column=2)
label_mand.grid(row=9,column=2)
randvalue_start = random.randint(2, 592)
def reset():
os.execl(sys.executable, sys.executable, *sys.argv)
frame = LabelFrame(window,text="Input",padx=5, pady=5)
frame.grid(row=0,column=1,padx=10,pady=10)
btn2 = Button(frame,text = "Show answer", fg = "green" ,width=20 ,command=pinying_btn2)
btn3 = Button(frame,text = "clear", fg= "red", width=20 ,command=reset)
btn1 = Button(frame,text = "Next character", fg = "black" ,width=20,command=english_btn1)
words_label = Label(frame,text = "# of characters: " + str(row_count))
label1.grid(row=0,column=2, columnspan=2)
Label(window, text="", width=20, height=3, font=("TkDefaultFont", 15)).grid(row=8, column=1)
label_blk1 = Label(window, text="", font=("TkDefaultFont", 15), width=10, height=3).grid(row=8, column=2)
label_blk2 = Label(window, text="", font=("TkDefaultFont", 30), width=10, height=2, padx=1, pady=1).grid(row=9, column=2)
btn1.grid(padx=5, pady=5)
btn2.grid(padx=5, pady=5)
btn3.grid(padx=5, pady=5)
words_label.grid(padx=5,pady=5)
window.mainloop()
This is not really a question about Pyxl or Excel. The question is really: how do you generate random numbers that skip certain numbers.
from random import randint
n = 592
numbers = list(range(n))
# To get a random number from the list
random_number = numbers[randint(0, len(numbers)-1)]
# To remove 123 from the list
numbers.remove(123)

root = Tk(), are there any alternatives?

does anyone know any alternatives for:
root = tk()
when i run my program, multiple windows run at the same time, just wondering whether there is an alternative so that they both dont open at the same time. The second window that opens as soon as the program is run should be launched when a button on the initial window is pressed. I also tried using:
root = Toplevel()
but the results are the same.
any ideas? thanks
def Search_Inventory():
#---First Window----
root = Toplevel()
root.title("Warehouse Inventory Control System")
root.configure(bg = "black")
#----Title displayed under the company logo on the first window----
Title_Screen = Label(root,
text="Warehouse Inventory Control System",
fg="grey",
bg="black",
font="Helevetica 25 bold",
pady = "50",
padx = "50",
).grid(row=3, column=4)
#----Interactive Input Boxes for the User----
#----Label to Notify what is needed in the entry box----
PN_Info_Label = Label(root,
text = "Part Number:",
fg="white",
bg="black",
font="Helevetica 15 bold",
padx = 50,
).grid(row=14, column=3, rowspan = 2)
#----Input Box for Part Number
PN_Display = StringVar()
Input_PartNumber = Entry(root,
textvariable=PN_Display,
fg = "blue",
font = "Helevtica 25 bold",
).grid(row=14, column=4)
#----A button that will proceed to the next part of the program----
Search_Button = Button(root,
text = "Search Inventory",
fg = "Blue",
bg = "Grey",
bd = 2,
font="Helevetica 15 bold",
command=lambda:Search_Prod(PN_Display.get()),
height = 1,
width = 15,
).grid(row=16, column=4,pady = 25,padx = 25,)
#----Information regarding how to enter the part number---
Info = Label(root,
text="Please Use Capitals to Enter Part Number",
fg= "red",
bg = "black",
font = "helevetica 12 bold",
).grid(row = 15, column = 4)
#----Adding the company logo to the first window----
photo = PhotoImage(file="image.gif")
photoLabel = Label(image=photo)
photoLabel.image = photo
photoLabel.grid(row=1, column=4, pady = 10)
#----Linking the Help Document----
Help_Button = Button(root,
text = "Help",
command=Help_PDF,
fg = "Red",
bg = "Black",
height = "1",
bd = "2",
font = "Helevetica 20 bold",
width = "4",
).grid(row=0, column=5, pady= 10,padx = 50, sticky = E)
#----Saying who the program was made by----
Credits = Label(root,
text = "Created By: Me",
fg = "White",
bg = "Black",
font = "Helevetica 10 underline",
).grid(row = 19, column = 5)
#To Make Sure that the window doesn't close
root.mainloop()
thats the subroutine that meant to run later but runs straight away.
root_menu = frame()
root_menu.title("Warehouse Inventory Control System")
root_menu.configure(bg = "black")
photo = PhotoImage(file="logo.gif")
photoLabel = Label(image=photo)
photoLabel.image = photo
photoLabel.grid(row=1, column=3,columnspan = 4, sticky = N)
Title_Screen = Label(root_menu,
text="Welcome to the SsangYong\n Warehouse Inventory Control System",
fg="grey",
bg="black",
font="Helevetica 25 bold",
pady = "50",
padx = "50",
).grid(row=2, column=3)
Search_Inventory = Button(root_menu,
command = Search_Inventory(),
text = "Search Inventory",
fg = "Blue",
bg = "Grey",
bd = 2,
font="Helevetica 12 bold",
height = 1,
width = 50,
).grid(row=16, column=3,pady = 25,padx = 25,)
Add_Stock = Button(root_menu,
text = "Add New Items",
fg = "Blue",
bg = "Grey",
bd = 2,
font="Helevetica 12 bold",
height = 1,
width = 60,
).grid(row=15, column=3,pady = 25,padx = 25,)
Print_Report = Button(root_menu,
text = "Print Stock Report",
fg = "Blue",
bg = "Grey",
bd = 2,
font="Helevetica 12 bold",
height = 1,
width = 70,
).grid(row=17, column=3,pady = 25,padx = 25,)
Help_Button = Button(root_menu,
text = "Help",
command=Help_PDF,
fg = "Red",
bg = "Black",
height = "1",
bd = "2",
font = "Helevetica 20 bold",
width = "4",
).grid(row=1, column=3,rowspan = 2, sticky= NE)
Credits = Label(root,
text = "Created By:mk",
fg = "White",
bg = "Black",
font = "Helevetica 10 underline",
).grid(row = 19, column = 5)
root_menu.mainloop()
this is what is meant to pop up initially but comes completely mixed up with the other one.
does anyone know any alternatives for: root = tk() [sic]
There is no alternative. A tkinter application absolutely must have a single root window. If you do not explicitly create one (and you should), one will be created for you the first time you create any other widget.
The second window that opens as soon as the program is run should be launched when a button on the initial window is pressed.
The reason for this is that you are telling it to open immediately. Take a look at this code:
Search_Inventory = Button(root_menu,
command = Search_Inventory(),
The above code is identical to this:
result = Search_Inventory()
Search_Inventory = Button(root_menu, command=result)
Notice the lack of () on the command. The command attribute requires a reference to a function.
command= needs function name - callback - it means without ()
But you have () in
command = Search_Inventory()
and this is why this is executed at start, not when you click button
BTW: tkinter need only one mainloop() - if you use two mainloop() then it works incorrectly.
EDIT: Problem with image is because you didn't set parent for Label in second window
photoLabel = Label(image=photo)
so it used main window as default
You need
photoLabel = Label(root, image=photo)
EDIT: minimal working code
from tkinter import *
def Help_PDF():
pass
def Search_Inventory():
#--- Second Window ----
root = Toplevel()
Title_Screen = Label(root, text="Warehouse Inventory Control System")
Title_Screen.grid(row=3, column=4)
PN_Info_Label = Label(root, text="Part Number:")
PN_Info_Label.grid(row=14, column=3, rowspan=2)
PN_Display = StringVar()
Input_PartNumber = Entry(root, textvariable=PN_Display)
Input_PartNumber.grid(row=14, column=4)
Search_Button = Button(root, text="Search Inventory",
command=lambda:Search_Prod(PN_Display.get()))
Search_Button.grid(row=16, column=4, pady=25, padx=25)
Info = Label(root, text="Please Use Capitals to Enter Part Number")
Info.grid(row=15, column=4)
photo = PhotoImage(file="image.gif")
photoLabel = Label(root, image=photo)
photoLabel.image = photo
photoLabel.grid(row=1, column=4, pady=10)
Help_Button = Button(root, text="Help",
command=Help_PDF)
Help_Button.grid(row=0, column=5, pady=10, padx=50, sticky=E)
Credits = Label(root, text="Created By: Me")
Credits.grid(row=19, column=5)
# --- First Window ---
root_menu = Tk()
photo = PhotoImage(file="logo.gif")
photoLabel = Label(root_menu, image=photo)
photoLabel.image = photo
photoLabel.grid(row=1, column=3, columnspan=4, sticky=N)
Title_Screen = Label(root_menu, text="Welcome to the SsangYong\n Warehouse Inventory Control System",)
Title_Screen.grid(row=2, column=3)
Search_Inventory = Button(root_menu, text="Search Inventory",
command=Search_Inventory)
Search_Inventory.grid(row=16, column=3, pady=25, padx=25)
Add_Stock = Button(root_menu, text="Add New Items")
Add_Stock.grid(row=15, column=3, pady=25, padx=25)
Print_Report = Button(root_menu, text="Print Stock Report")
Print_Report.grid(row=17, column=3, pady=25, padx=25)
Help_Button = Button(root_menu, text="Help",
command=Help_PDF)
Help_Button.grid(row=1, column=3, rowspan=2, sticky=NE)
Credits = Label(root_menu, text="Created By:mk")
Credits.grid(row=19, column=5)
root_menu.mainloop()

How to update Labels in tkinter?

I'm trying to create a program in where you put a word in a box, press add, and this word goes to a list, which is also displayed on the right side. When I press the forward button the first thing on the list is deleted. Problem is I can't get the labels to update when I press the buttons / edit the list.
from tkinter import *
root = Tk()
root.title('Speakers List')
root.minsize(800, 600)
speakers = ['none']
spe = speakers[0]
def add():
if spe == 'none':
speakers.insert(0, [s])
e.delete(0, END)
spe.config(text=speakers[0])
else:
speakers[-2] = [s]
e.delete(0, END)
spe.config(text=speakers[0])
return
def forward():
if len(speakers) is 0:
return
else:
del speakers[0]
spe.config(text=speakers[0])
return
entry = StringVar()
e = Entry(root, width=30, font=("Arial", 20), textvariable=entry)
e.grid(row=0, sticky=W)
s = e.get()
button1 = Button(root, padx=10, pady=10, bd=5, text='Add', fg='black', command=add)
button1.grid(row=0, column=1)
button2 = Button(root, padx=10, pady=10, bd=5, text='Next', fg='black', command=forward)
button2.grid(row=1, column=1)
n = Label(root, font=("Arial", 35), bd=2, text=spe)
n.grid(row=1, sticky=W)
listdisplay = Label(root, font=('Arial', 20), text=speakers)
listdisplay.grid(row=0, column=10)
root.mainloop()
Is this the sort of thing you were looking for ?
from tkinter import *
root = Tk()
root.title('Speakers List')
root.minsize(800, 600)
speakers = ['50']
spe = speakers[0]
def add():
entry=e.get()
speakers.append(entry)
listdisplay.config(text=speakers)
return
def forward():
if len(speakers) is 0:
return
else:
del speakers[0]
listdisplay.config(text=speakers)
spe=speakers[0]
n.config(text=spe)
return
entry = StringVar()
e = Entry(root, width=30, font=("Arial", 20), textvariable=entry)
e.grid(row=0, sticky=W)
s = e.get()
button1 = Button(root, padx=10, pady=10, bd=5, text='Add', fg='black',command=add)
button1.grid(row=0, column=1)
button2 = Button(root, padx=10, pady=10, bd=5, text='Next', fg='black',command=forward)
button2.grid(row=1, column=1)
n = Label(root, font=("Arial", 35), bd=2, text=spe)
n.grid(row=1, sticky=W)
listdisplay = Label(root, font=('Arial', 20), text=speakers)
listdisplay.grid(row=0, column=10)
root.mainloop()
If so:
You create a list and then you use the append function to add an item to it. The rest was pretty much right.

Categories