How to delete text from Tkinter? - python

I want to know how do u delete text inside the Tkinter. The text is circled in red.
My code is as below:
from tkinter import *
from tkinter.ttk import Combobox
import win32com.client
root = Tk()
root.title('PM1 Digital Checklist')
root.geometry("400x400")
def open_excel():
if combo.get() == 'PPM8001':
myLabel = Label(root, text="Prime Mover Number Selected is:").pack()
myLabel = Label(root, text=combo.get()).pack()
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True
file = excel.Workbooks.Open(r"/path/to/PPM8001.xlsx")
if combo.get() == 'PPM8002':
myLabel = Label(root, text="Prime Mover Number Selected is:").pack()
myLabel = Label(root, text=combo.get()).pack()
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True
file = excel.Workbooks.Open(r"/path/to/PPM8002.xlsx")
if combo.get() == 'PPM8003':
myLabel = Label(root, text="Prime Mover Number Selected is:").pack()
myLabel = Label(root, text=combo.get()).pack()
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True
file = excel.Workbooks.Open(r"/path/to/PPM8003.xlsx")
options = ['PPM8001','PPM8002','PPM8003']
v = list(options)
combo = Combobox(root, values = v, width =40)
combo.set("Select which Prime Mover number")
combo.pack()
button = Button(root, text = "Select", command = open_excel).pack()
root.mainloop()
The image is here:

There are 2 things to fix:
use
myLabel = Label(root, text="Prime Mover Number Selected is:")
myLabel.pack()
To actually put a Label instance into a variable
use
myLabel.destroy()
To get rid of it.
Hope that's helpful!

Related

Text Field that appears if user choose Yes in the combo box in tkinter

I want to add a text field and input text if the user choose "Yes" in the combo box; other wise nothing will be added. Tried this but didn't work
Combo = ttk.Combobox(window, values = vlist)
Combo.set("Pick an Option")
Combo.pack()
if (Combo.get()=="Yes"):
tkinter.Label(window, text="Number of Workers", bg = "white",fg = "black", font=("Times",13,"bold")).place(x=155,y=240)
inputtxt3 = Text(window, height = 1, width = 25, bg = "light yellow")
inputtxt3.pack()
inputtxt3.place(x=325, y=238)
Does this help you?
from tkinter import Tk, StringVar
from tkinter.ttk import Label, Combobox, Button
root = Tk()
def check(): # For checking the value of ComboBox
combo_value = var.get()
if combo_value == "Yes":
lbl.config(text="You selected 'Yes'")
else:
lbl.config(text="You selected 'No'")
var = StringVar() # To store the value of the Combobox
Combo = Combobox(root, values=["Yes", "No"], textvariable=var)
Combo.pack(pady=20)
btn = Button(root, text="Confirm", command=check)
btn.pack(pady=20)
lbl = Label(root)
lbl.pack(pady=20)
root.mainloop()

The if condition does not work as expected in Tkinter

I've been having some troubles with this code as the if condition cannot be true and always executes the else condition instead.
can you help
`
from tkinter import *
root = Tk()
entry_1 =Entry(root, width = 20)
entry_1.pack()
entry_1.insert(0, "Choose Your Number ")
def m():
answer = entry_1.get().strip()
if answer == 5 :
mylabel = Label(root, text = "YOU WIN!")
mylabel.pack()
else :
mylabel = Label(root, text = "YOU LOST!")
mylabel.pack()
mybutton = Button(root, text = 'PLAY', command = m)
mybutton.pack()
root.mainloop()
Thanks
Any user input is a string, so you need to convert to an Integer.
Try this code:
from tkinter import *
root = Tk()
entry_1 =Entry(root, width = 20)
entry_1.pack()
entry_1.insert(0, "Choose Your Number ")
def m():
answer = int(entry_1.get().strip())
if answer == 5 :
mylabel = Label(root, text = "YOU WIN!")
mylabel.pack()
else :
mylabel = Label(root, text = "YOU LOST!")
mylabel.pack()
mybutton = Button(root, text = 'PLAY', command = m)
mybutton.pack()
root.mainloop()

How to get value from Entry in Python tkinter? [duplicate]

This question already has answers here:
Tkinter: AttributeError: NoneType object has no attribute <attribute name>
(4 answers)
Closed 3 years ago.
The code I have attached below functions like this: It takes users ID and marks. It goes through an excel sheet and finds that specific ID. Then it will update the second column in that row with his marks.
However, this code gives me an error when I run it. The error comes from .get() function used for getting value of an Entry. I have used .get() function in other projects where it works.
import xlwt
import xlrd
from xlutils.copy import copy
from tkinter import *
root = Tk()
root.title("Quiz marks uploader")
root.geometry("500x500")
rnn = "global"
maar = "global"
def upload():
rn = entry_1.get()
mar = entry_2.get()
rnn = rn
maar = mar
button_1 = Button(root, text = "Upload", command = upload).place(relx = 0.3,rely = 0.2,anchor = NE)
label_1 = Label(root, text = "Enter Reg No here").place(relx = 0.2,rely = 0.05,anchor = E)
entry_1 = Entry(root).place(relx = 0.5,rely = 0.05,anchor = E)
label_2 = Label(root, text = "Enter marks here").place(relx = 0.2,rely = 0.1,anchor = E)
entry_2 = Entry(root).place(relx = 0.5,rely = 0.1,anchor = E)
workbook = xlrd.open_workbook("file.xls")
sheet = workbook.sheet_by_index(0)
rb = xlrd.open_workbook("file.xls")
wb = copy(rb)
w_sheet = wb.get_sheet(0)
for row in range(sheet.nrows):
row_value = sheet.row_values(row)
if row_value[0] == rnn:
w_sheet.write(row,1,maar)
print (row_value)
wb.save("file.xls")
root.mainloop()
This is where you are going wrong:
You are doing:
entry_1 = Entry(root).place(relx = 0.5,rely = 0.05,anchor = E)
In this case, the entry_1 is a NoneType object.
And NoneType object doesn't have any property get(), therefore it throws an error.
What you should do:
First instantiate an Entry widget and then give your widget a position in the window using the widget reference.
entry_1 = Entry(root)
entry_1.place(relx = 0.5,rely = 0.05,anchor = E)
Updated code:
import xlwt
import xlrd
from xlutils.copy import copy
from tkinter import *
root = Tk()
root.title("Quiz marks uploader")
root.geometry("500x500")
rnn = "global"
maar = "global"
def upload():
rn = entry_1.get()
mar = entry_2.get()
rnn = rn
maar = mar
button_1 = Button(root, text = "Upload", command = upload).place(relx = 0.3,rely = 0.2,anchor = NE)
label_1 = Label(root, text = "Enter Reg No here").place(relx = 0.2,rely = 0.05,anchor = E)
# entry widget 1
entry_1 = Entry(root)
entry_1.place(relx = 0.5,rely = 0.05,anchor = E)
label_2 = Label(root, text = "Enter marks here").place(relx = 0.2,rely = 0.1,anchor = E)
# entry widget 2
entry_2 = Entry(root)
entry_2.place(relx = 0.5,rely = 0.1,anchor = E)
workbook = xlrd.open_workbook("file.xls")
sheet = workbook.sheet_by_index(0)
rb = xlrd.open_workbook("file.xls")
wb = copy(rb)
w_sheet = wb.get_sheet(0)
for row in range(sheet.nrows):
row_value = sheet.row_values(row)
if row_value[0] == rnn:
w_sheet.write(row,1,maar)
print (row_value)
wb.save("file.xls")
root.mainloop()
Hope it helps!
Instead of xlrd use pandas for managing excel files.
To create simple excel file:
import pandas as pd
df = (pd.DataFrame({'ID': [10, 11, 12], 'Mark': ['ww','zz','cc']}))
df.to_excel('data.xlsx')
I add some changes in elements positions.
Now you can update data like below:
import pandas as pd
from tkinter import *
root = Tk()
root.title("Quiz marks uploader")
root.geometry("500x500")
def upload():
id = entry_id.get()
mark = entry_mark.get()
# load excel into data frame
df = pd.read_excel('data.xlsx', index_col=0)
# find proper row and replace value
row_match = df[df['ID'] == int(id)]
if row_match.shape[0] > 0:
df.at[row_match.index[0], 'Mark'] = mark
# save updated file
df.to_excel('data.xlsx')
# set button and labels
button = Button(root, text = "Upload", command=upload)
button.grid(column=1, row=4)
label = Label(root, text = "Id")
label.grid(column=0, row=2)
entry_id = Entry(root)
entry_id.grid(column=1, row=2)
label = Label(root, text = "Mark")
label.grid(column=0, row=3)
entry_mark = Entry(root)
entry_mark.grid(column=1, row=3)
root.mainloop()

I cant generate a random number and print it

I can't generate the number because I get the error NameError: name 'z' is not defined.
import tkinter as tk
from random import randint
def randomize():
z.set ( randint(x.get(),y.get()))
root = tk.Tk()
x = tk.IntVar()
y = tk.IntVar()
text= tk.Label(root, text = "press the button for random number")
enterX = tk.Entry(root)
enterY = tk.Entry(root)
button = tk.Button(root, text = "Press here", command=randomize)
result = tk.Label(root,text="Number is:")
number = tk.Label(root, textvariable=z)
text.pack()
enterX.pack()
enterY.pack()
button.pack()
result.pack()
number.pack()
root.mainloop()
I need help to resolve the error
You have 2 problems here.
One. You are missing z = tk.Intvar() in the global namespace.
Two. You need to assign each entry field one of the IntVar()'s.
Keep in mind that you are not validating the entry fields so if someone types anything other than a whole number you will run into an error.
Take a look at this code.
import tkinter as tk
from random import randint
def randomize():
z.set(randint(x.get(),y.get()))
print(z.get()) # added print statement to verify results.
root = tk.Tk()
x = tk.IntVar()
y = tk.IntVar()
z = tk.IntVar() # added IntVar()
text= tk.Label(root, text = "press the button for random number")
enterX = tk.Entry(root, textvariable=x) # added textvariable
enterY = tk.Entry(root, textvariable=y) # added textvariable
button = tk.Button(root, text = "Press here", command=randomize)
result = tk.Label(root,text="Number is:")
number = tk.Label(root, textvariable=z)
text.pack()
enterX.pack()
enterY.pack()
button.pack()
result.pack()
number.pack()
root.mainloop()

How do I add a function result string on the tkinter window?

I am new in python and trying to make a program for converting a given string into a secret code. The string entered by user in the text box is taken as input and converted in secret code (using the encryption module). How do I display the result in the window (I tried using the label but it shows an error.)
from tkinter import *
import encryption as En # Loading Custom libraries
import decryption as De
out_text = None # Out text is the output text of message or the encryption
root = None
font_L1 = ('Verdana', 18, 'bold') # The font of the header label
button1_font = ("Ms sans serif", 8, 'bold')
button2_font = ("Ms sans serif", 8, 'bold')
font_inst = ("Aerial", 8)
my_text = None
input_text = None
text_box = None
resut_l = None
result_2 = None
def b1_action(): # Encryption button
input_text = text_box.get()
if input_text == "":
print("Text field empty")
else:
En.enc_text(input_text) # Message is returned as 'code'
def b2_action():
input_text = text_box.get()
if input_text == "":
print("Text field Empty")
else:
De.dec_text(input_text)
def enc_button(): # Button for rendering encryption
b1 = Button(root, text = "ENCRYPT", font = button1_font, command = b1_action)
b1.configure(bg = 'palegreen3', width = '10', height = '3')
b1.place(x = '120', y = '130')
def dec_button(): # Button for decryption
b2 = Button(root, text = "DECRYPT", font = button2_font, command = b2_action)
b2.configure(bg = 'palegreen3', width = '10', height = '3')
b2.place(x = '340', y = '130')
def main(): #This is the core of GUI
global root
global text_box
root = Tk()
root.geometry("550x350")
root.configure(bg = "MediumPurple1")
win_text = Label(root, text = 'Enter text below and Choose an action:', bg = 'MediumPurple1', font = font_L1)
win_text.place(x = '10', y = '50')
text_box = Entry(root, text = 'Enter the Text', width = 60, bg = 'light blue')
text_box.place(x = '100', y = '100')
inst_text = Label(root, text = instructions, bg = "MediumPurple1", font = font_inst)
inst_text.pack(side = BOTTOM)
enc_button()
dec_button()
root.title('Secret Message.')
root.mainloop()
main()
And here is the encryption module
def enc_text(line):
msg = str(line).replace(' ', '_').lower()
msg_list = list(msg)
all_char = list("abcdefghijklmnopqrstuvwxyzabc_!?#")
for i in range(0, len(msg)):
pos_replaced = all_char.index(str(msg_list[i])) #will give the positon of the word to be replaced in the main list of alphabets
msg_list.insert(i, all_char[pos_replaced + 3]) #will replace the elements one by one
msg_list.pop(i + 1)
i += 1
code = ''.join(msg_list).replace('#', ' ')
print(code)
You can also suggest some improvisations.
Part of the problem is that Entry widgets don't have a text= configuration option, so it's completely ignored in the line:
text_box = Entry(root, text='Enter the Text', width=60, bg='light blue')
The best way to handle the character contents of an Entry is by using its textvariable= option and setting the value of it to be an instance of a tkinter.StringVar, then the getting and setting the value of that object will automatically update the Entry widget on the screen.
Below is your code with changes made to it to do this. Note I commented and changed a few unrelated things to be able to run the code, but tried to indicate the most important ones. Also note I added a return code statement at the very end of the enc_text() function in your custom encryption module.
from tkinter import *
import encryption as En # Loading Custom libraries
#import decryption as De # DON'T HAVE THIS.
out_text = None # Out text is the output text of message or the encryption
root = None
font_L1 = ('Verdana', 18, 'bold') # The font of the header label
button1_font = ("Ms sans serif", 8, 'bold')
button2_font = ("Ms sans serif", 8, 'bold')
font_inst = ("Aerial", 8)
my_text = None
input_text = None
text_var = None # ADDED.
text_box = None
resut_l = None
result_2 = None
# CHANGED TO USE NEW "text_var" variable.
def b1_action(): # Encryption button
input_text = text_var.get()
if input_text == "":
print("Text field empty")
else:
text_var.set(En.enc_text(input_text))
def b2_action():
input_text = text_box.get()
if input_text == "":
print("Text field Empty")
else:
"""De.dec_text(input_text)"""
def enc_button(): # Button for rendering encryption
b1 = Button(root, text="ENCRYPT", font=button1_font, command=b1_action)
b1.configure(bg='palegreen3', width='10', height='3')
b1.place(x='120', y='130')
def dec_button(): # Button for decryption
b2 = Button(root, text="DECRYPT", font=button2_font, command=b2_action)
b2.configure(bg='palegreen3', width='10', height='3')
b2.place(x='340', y='130')
def main(): #This is the core of GUI
global root
global text_box
global text_var # ADDED
root = Tk()
root.geometry("550x350")
root.configure(bg="MediumPurple1")
win_text = Label(root, text='Enter text below and Choose an action:',
bg='MediumPurple1', font=font_L1)
win_text.place(x='10', y='50')
text_var = StringVar() # ADDED
text_var.set('Enter the Text') # ADDED
# CHANGED text='Enter the Text' to textvariable=text_var
text_box = Entry(root, textvariable=text_var, width=60, bg='light blue')
text_box.place(x='100', y='100')
inst_text = Label(root, text="instructions", bg="MediumPurple1",
font=font_inst)
inst_text.pack(side=BOTTOM)
enc_button()
dec_button()
root.title('Secret Message.')
root.mainloop()
main()

Categories