NameError: name 'Radiobutton' is not defined - python

I am constructing a messaging application, and using Tkinter for GUI. I am trying to create some buttons, but I receive an error message:
Traceback (most recent call last):
File "/home/artur/Documents/MScProject/MSc Project/Task #179276/main_program.py", line 174, in <module>
app = Application(the_window)
File "/home/artur/Documents/MScProject/MSc Project/Task #179276/main_program.py", line 49, in __init__
self.AES_radiobutton = Radiobutton(text = 'AES algorithm', bg = color, variable=self.var, value=0)
NameError: name 'Radiobutton' is not defined
I am posting all of the source code here:
import tkinter as tk
from tkinter import IntVar
from tkinter import messagebox
from tkinter import Frame
from tkinter import Frame
from tkinter import Text
from tkinter import Label
from AESEncDec import *
from MD5Hashing import *
from RSAEncDec import *
color = 'lightblue' #color our background
class Application(Frame):
def __init__(self, root=None):
Frame.__init__(self, root)
self.frame_width = 700
self.frame_height = 400
# Set configuration our frame
self.config(width = self.frame_width, height = self.frame_height, bg = color)
self.pack()
# Create textBox for input data
self.textbox_one = Text()
self.textbox_one.place(x = 30, y = 170, height = 200, width = 300 )
# Create textBox for result
self.textbox_two = Text()
self.textbox_two.place(x = 370, y = 170, height = 200, width = 300 )
label_input_text = Label( text = "Input text: ", bg = color)
label_input_text.place(x = 30, y = 155, height = 10, width = 70 )
label_output_text = Label( text = "Result: ", bg = color)
label_output_text.place(x = 370, y = 155, height = 10, width = 50 )
# IntVar help to detect, what radioButton was chosen
self.var = IntVar()
# Create radioButton for AES
self.AES_radiobutton = Radiobutton(text = 'AES algorithm', bg = color, variable=self.var, value=0)
self.AES_radiobutton.place(x = 100, y = 20, height = 30, width = 100 )
# Create radioButton for DSA
self.DSA_radiobutton = Radiobutton(text = 'DSA algorithm', bg = color, variable=self.var, value=1)
self.DSA_radiobutton.place(x = 100, y = 70, height = 30, width = 100 )
# Create radioButton for Hash function
self.HF_radiobutton = Radiobutton(text = 'Hash function', bg = color, variable=self.var, value=2)
self.HF_radiobutton.place(x = 100, y = 120, height = 30, width = 100 )
# Create label
self.lable_for_ask_bits = Label(text = 'Input size of bits:', bg = color)
self.lable_for_ask_bits.place(x = 210, y = 70, height = 30, width = 100 )
# Create textBox for input bits
self.input_bits = Text()
self.input_bits.place(x = 310, y = 75, height = 20, width = 50 )
self.input_bits.insert(INSERT, '16')
# Create button to encrypt text
self.encrypt_button = Button(root, text = "Encrypt text", command = self.encrypt_text)
self.encrypt_button.place(x = 420, y = 20, height = 80, width = 100 )
# Create button to decrypt text
self.decrypt_button = Button(root, text = "Decrypt text", command = self.decrypt_text)
self.decrypt_button.place(x = 540, y = 20, height = 80, width = 100 )
# Create button to hash
self.hash_button = Button(root, text = "Hash text", command = self.hashing )
self.hash_button.place(x = 420, y = 120, height = 30, width = 220)
# Create AES object, keyword "this is a very strong key"
# You can change keyword
self.AES = AESEncDec('this is a very strong key')
# Save bits
self.bit_length = 16
# Create RSA object
self.RSA = RSAEncDec(self.bit_length)
def encrypt_text(self):
self.textbox_two.delete("1.0", END)
# Get radioButton selection
selection = self.var.get()
# if chosen AES
if selection == 0:
# Read text from input
message = self.textbox_one.get("1.0", END)
encrypt_message = self.AES.encrypt(message)
# Output result
self.textbox_two.insert(INSERT, encrypt_message)
# if chosen RSA
elif selection == 1:
try:
# Read number of bits
tmp_bits = int(self.input_bits.get("1.0", END))
# if bits not in range from 4 to 32 print error message
if tmp_bits < 4 or tmp_bits > 32:
tkMessageBox.showerror(message ='Bits must be in range from 4 to 32')
else:
# else, if tmp_bits not = self.bit_length: create new object
if tmp_bits != self.bit_length:
self.bit_length = tmp_bits
self.RSA = RSAEncDec(self.bit_length)
except:
tkMessageBox.showerror(message ='You must input integer number')
# Find max number
max_number = self.RSA.get_max_value_to_encrypt()
try:
# Read text from input (myst be number)
message = int(self.textbox_one.get("1.0", END))
if message < 0 or message > max_number:
tkMessageBox.showerror(message ='Input text must be number in range from 0 to ' + str(max_number))
else:
encrypt_message = self.RSA.encrypt(message)
# Output result
self.textbox_two.insert(INSERT, encrypt_message)
except:
tkMessageBox.showerror(message ='Input text must be number in range from 0 to ' + str(max_number))
else:
tkMessageBox.showinfo(message ='You must select "AES" or "RSA" radioButton')
def decrypt_text(self):
self.textbox_two.delete("1.0", END)
# Get radioButton selection
selection = self.var.get()
# if chosen AES
if selection == 0:
# Read text from input
message = self.textbox_one.get("1.0", END)
decrypt_message = self.AES.decrypt(message)
# Output result
self.textbox_two.insert(INSERT, decrypt_message)
elif selection == 1:
# Read text from input
message = int(self.textbox_one.get("1.0", END))
decrypt_message = self.RSA.decrypt(message)
# Output result
self.textbox_two.insert(INSERT, decrypt_message)
else:
tkMessageBox.showinfo(message ='You must select "AES" or "RSA" radioButton')
def hashing(self):
# Get radioButton selection
selection = self.var.get()
# if chosen Hash function
if selection == 2:
# Read text from input
message = self.textbox_one.get("1.0", END)
# Hashing
hashing_message = Hashing(message)
# Output result
self.textbox_two.insert(INSERT, hashing_message)
else:
tkMessageBox.showinfo(message ='You must select "Hash function" radioButton')
#create object TK class
the_window = tk.Tk(className = " Cryptographic")
#create object Application
app = Application(the_window)
#run our Application
app.mainloop()
I still see the GUI though and an input box, but a lot of elements are missing. What might be the problem here?

Simple import of Radiobutton module solved the issue

Related

Why is my Tkinter button command ignoring the arguments I'm sending into a function?

I'm attempting to create a GUI for astrophotography, and am trying to add a function that would allow choosing a specific directory for files. I'm using a button with a command, and am trying to run the function (that has an argument) using the lambda function. However, trying to run it I was given a TypeError: uploadFlats() missing 1 required positional argument: 'x'.
class Astrophotography:
def __init__(self):
self.mainWin = tk.Tk()
self.mainWin.title("Automatic Image Editor")
self.firstFrame = tk.Frame(self.mainWin, width = 600, height = 200)
self.secondFrame = tk.Frame(self.mainWin)
self.thirdFrame = tk.Frame(self.mainWin)
# First Frame
self.description = tk.Label(self.firstFrame, text = "Please select a save directory and also directories\
for flats, biases, and darks to create masters of each")
self.flatsLabel = tk.Label(self.firstFrame, text = "Please enter flats directory: ")
self.flatsText = tk.StringVar(value = "")
self.flatsEntry = tk.Entry(self.firstFrame, width = 50, textvariable = self.flatsText)
self.browseflats = tk.Button(self.firstFrame, text = "Browse",
command = lambda: self.uploadFlats(self.flatsText))
self.flatsLabel = tk.Label(self.firstFrame, text = "Please enter flats directory: ")
self.flatsText = tk.StringVar()
self.flatsEntry = tk.Entry(self.firstFrame, width = 50, textvariable = self.flatsText)
self.browseflats = tk.Button(self.firstFrame, text = "Browse", command = self.uploadFlats)
self.darksLabel = tk.Label(self.firstFrame, text = "Please enter darks directory: ")
self.darksText = tk.StringVar()
self.darksEntry = tk.Entry(self.firstFrame, width = 50, textvariable = self.darksText)
self.browsedarks = tk.Button(self.firstFrame, text = "Browse", command = self.uploadDarks)
self.biasLabel = tk.Label(self.firstFrame, text = "Please enter bias directory: ")
self.biasText = tk.StringVar()
self.biasEntry = tk.Entry(self.firstFrame, width = 50, textvariable = self.biasText)
self.browsebias = tk.Button(self.firstFrame, text = "Browse", command = self.uploadBias)
self.enterButton = tk.Button(self.firstFrame, text = "Create Masters", command = self.mastercalibrations)
#-----------------------------------------------------------------------------------------------------------------------
# Placement
self.firstFrame.pack()
self.secondFrame.pack(side = 'left', padx = 5, pady = 5)
self.thirdFrame.pack(side = 'right', padx = 5, pady = 5)
#First Frame
self.initialY = 5
self.spacing = 30
self.description.place(x = 5, y = 5)
self.flatsLabel.place(x = 5, y = self.initialY + self.spacing)
self.flatsEntry.place(x = 200, y = self.initialY + self.spacing)
self.browseflats.place(x = 510, y = self.initialY + self.spacing)
self.darksLabel.place(x = 5, y = self.initialY + 2 * self.spacing)
self.darksEntry.place(x = 200, y = self.initialY + 2 * self.spacing)
self.browsedarks.place(x = 510, y = self.initialY + 2 * self.spacing)
self.biasLabel.place(x = 5, y = self.initialY + 3 * self.spacing)
self.biasEntry.place(x = 200, y = self.initialY + 3 * self.spacing)
self.browsebias.place(x = 510, y = self.initialY + 3 * self.spacing)
self.enterButton.place(x = 5, y = self.initialY + 4 * self.spacing)
self.mainWin.mainloop()
#-----------------------------------------------------------------------------------------------------------------------
def uploadFlats(self, entry):
self.directory = dlg.askdirectory()
#Delete current text in image name entry and replace with found image name
entry.set(0, self.directory)
def uploadDarks(self):
self.directory = dlg.askdirectory()
#Delete current text in image name entry and replace with found image name
self.darksEntry.delete(0, 'end')
self.darksEntry.insert(0, self.directory)
def uploadBias(self):
self.directory = dlg.askdirectory()
#Delete current text in image name entry and replace with found image name
self.biasEntry.delete(0, 'end')
self.biasEntry.insert(0, self.directory)
def mastercalibrations(self):
print('m')
I have tried using lambda functions, the partial function, and have tried seeing if it is just an issue with the my function itself. Regardless of what the uploadFlats actually does, I'm given this same error. I have tried sending in multiple different types of variables, however they are all consistently ignored.

The tkinter entry widget get function in attend is not returning anything

I am trying to make an attendance app for my lecture. Here I got stuck when dealing with tkinter widget.
from functools import partial
from tkinter import *
from tkinter import messagebox
from tkcalendar import Calendar, DateEntry
# def focus_course(event):
# course_name.focus_set()
# def focus_topic(event):
# topic_name.focus_set()
# def focus_studN(event):
# student_name.focus_set()
ca=StringVar
ta=StringVar
sname=StringVar
**
def attend(courseN,topicN,studN):
ca=(courseN.get())
ta=(topicN.get())
sname=(studN.get())
if((ca != "") or (ta != "") or (sname != "")):
messagebox.showinfo("success", "all fields save")
print("hello")
else:
print("printing")
messagebox.showinfo("error", "please enter all fields")
**
if __name__=="__main__":
# global submit_button
# global course_name
# global topic_name
# global student_name
top = Tk()
top.geometry("450x300")
# the label for user_name
# the label for user_password
dlabel = Label(top,
text = "Date").place(x = 40,
y = 22)
dlabel = Label(top,
text = "Course").place(x = 40,
y = 60)
topic = Label(top,
text = "Topic").place(x = 40,
y = 100)
students = Label(top,
text = "Students present").place(x = 40,
y = 140)
courseN=StringVar()
topicN=StringVar()
studN=StringVar()
date = DateEntry(top, width= 16, background= "magenta3", foreground= "white",bd=2)
course_name = Entry(top,width = 30,textvariable="courseN").place(x = 150,
y = 60)
topic_name = Entry(top,width = 30,textvariable="topicN").place(x = 150,
y = 100)
student_name = Entry(top,width= 30,textvariable="studN").place(x=150,y=140)
attend=partial(attend,courseN,topicN,studN)
submit_button = Button(top,
text = "Submit",command=attend).place(x = 120,
y = 180)
print(type(course_name))
# course_name.bind("<Return>", focus_course)
# topic_name.bind("<Return>", focus_topic)
# student_name.bind("<Return>", focus_studN)
date.pack(pady=20)
top.mainloop()
# startapp()
Here I tried lot of things but never succeed in one. What can I try next?

How do I get tkinter application to update as I change a text file needed?

I have a text file with values that I need to display in a scroll box tkinter. I have been succesful in doing this but there is a problem. When I press submit to add more values to my text file in my program, the scrollbox displaying the contents in the text file does not update with the new values.
Here is a screenshot of the program:
This is my text file:
amazon.com
username#gmail.com
n3*F/X"qse~a`_+
netflix.com
username#outlook.com
avOmCl|Jb?O<
apple.com
username#icloud.com
s=DT8n*Y"y
However when I press submit the text file updates with the values submitted but the scrollbox does not.
Here is my full code:
import string
import random
from tkinter import *
import tkinter.scrolledtext as st
mypasslist = []
with open("password&usernames.txt", "r") as input:
for line in input:
items = line.split()
mypasslist.append([item for item in items[0:]])
def generatePassword():
characters = string.ascii_letters + string.punctuation + string.digits
password = "".join(random.choice(characters) for x in range(random.randint(8, 16)))
return password
def writeToFile(input_variable):
with open("password&usernames.txt", "a") as input:
input.writelines(input_variable)
top = Tk()
top.geometry("1920x1080")
def ifSubmit():
global a
a = generatePassword()
label1 = Label(top, text='Your password is: %s' % a, font=("Arial", 11)).place(x = 40, y = 170)
label1 = Label(top, justify='left', text='Your password and username has been saved, you can access them below.').place(x = 40, y = 227)
copy_button = Button(top, text = 'Copy', command=copyText).place(x=40, y=195)
service = service_var.get()
username = username_var.get()
writeToFile('%s\n' % str(service))
writeToFile('%s\n' % str(username))
writeToFile('%s\n' % str(a))
writeToFile('\n')
def copyText():
top.clipboard_clear()
top.clipboard_append(a)
top.update()
# the label for user_name
Service = Label(top, text = "Service").place(x = 40, y = 60)
user_name = Label(top, text = "Username").place(x = 40, y = 100)
submit_button = Button(top, text = "Submit", command=ifSubmit)
submit_button.place(x = 40, y = 130)
service_var = StringVar()
Service_input_area = Entry(top, width = 30, textvariable=service_var)
Service_input_area.place(x = 110, y = 60)
service = service_var.get()
username_var = StringVar()
user_name_input_area = Entry(top, width = 30, textvariable=username_var)
username = username_var.get()
user_name_input_area.place(x = 110, y = 100)
text_area = st.ScrolledText(top, width = 50, height = 10)
text_area.grid(column = 0, pady = 260, padx = 40)
for i in mypasslist:
text_area.insert(INSERT, i)
text_area.insert(INSERT, '\n')
text_area.configure(state ='disabled')
top.mainloop()
So how could I make the program update every time new values have been submitted?
I got it working, I had to do:
def writeToFile(input_variable):
with open("password&usernames.txt", "a") as input:
input.writelines(input_variable)
text_area['state'] = NORMAL
text_area.insert(INSERT, input_variable)
text_area['state'] = DISABLED

Radiobuttons and Checkbuttons not appearing in window

I'm writing a program that draws a rectangle or oval in a top frame depending on whether or not the user selects it via a radiobutton. There is a check button that determines whether the oval is filled as well. Both buttons are on the bottom frame. But for some reason when I run the code, it displays the window, but not the buttons themselves. How do I fix this?
Here's my code:
from tkinter import *
class GeometricFigures:
def __init__(self):
self.window = Tk()
self.window.title("Radiobuttons and Checkbuttons")
self.canvas = Canvas(self.window, width = 300, height = 100, bg = "white")
self.canvas.pack()
def drawButtons(self):
self.bottomframe = Frame(self.window)
self.bottomframe.pack()
self.check = IntVar()
cbtFilled = Checkbutton(self.bottomframe, variable = self.check, value = 0,
text = "Filled", command = self.processCheckbutton).pack(side = LEFT)
self.radio = IntVar()
rbRectangle = Radiobutton(self.bottomframe, variable = self.radio, value = 1,
text = "Rectangle", command = self.processRadiobutton.pack())
rbOval = Radiobutton(self.bottomframe, text = "Oval", variable = self.radio,
value = 2, command = self.processRadiobutton.pack())
cbtFilled.grid(row = 1, column = 2)
rbRectangle.grid(row = 1, column = 3)
rbOval.grid(row = 1, column = 4)
def processCheckbutton(self):
print("The check button is " +
("checked " if self.check.get() == 1 else "unchecked"))
def processRadiobutton(self):
print(("Rectangle" if self.radio.get() == 1 else "Oval")
+ " is selected ")
def drawRect(self):
self.canvas.create_rectangle(30, 10, 270, 60, tags = "rect")
def drawFillOval(self):
self.canvas.create_oval(30, 10, 270, 60, fill = 'blue', tags = "oval")
def drawOval(self):
self.canvas.create_oval(30, 10, 270, 60, tags = "oval")
def main(self):
test = GeometricFigures()
if self.check.get() == 1:
test.drawFillOval()
if self.radio.get() == 1:
test.drawRect()
else:
test.drawOval()
test.drawButtons()
if __name__ == '__main__':
main()
Thanks!

how to update a listbox in one window in one class using a different class python

what i have is a window that opens up and it has a list box. this is created using one class. when i click the search button and results are found using a different class, i want the list box to update without having to open up another window. below is my code so far\n
from Tkinter import *
class addTask:
def __init__(self):
self.addWindow = Tk()
self.addWindow.configure(background = "black")
self.addWindow.geometry("450x450")
self.addWindow.resizable(width = False, height = False)
self.addWindow.title("Add Task")
self.addNameLabel = Label(self.addWindow,text="Add the name of the task",font = ("Helvetica",10,"italic"),bg = "black",fg = "white")
self.addNameLabel.place(relx=0.01, rely=0.05)
self.nameWiget = Text (self.addWindow, width = 63, height = 1)
self.nameWiget.place(relx=0.0, rely=0.1)
self.addDateLabel = Label(self.addWindow,text="Add the date of the task",font = ("Helvetica",10,"italic"),bg = "black",fg = "white")
self.addDateLabel.place(relx=0.01, rely=0.2)
self.dateWiget = Text (self.addWindow, width = 63, height = 1)
self.dateWiget.place(relx=0.0, rely=0.25)
self.addTaskLabel = Label(self.addWindow,text="Add the details of the task",font = ("Helvetica",10,"italic"),bg = "black",fg = "white")
self.addTaskLabel.place(relx=0.01, rely=0.35)
self.taskWiget = Text (self.addWindow, width = 63, height = 1)
self.taskWiget.place(relx=0.0, rely=0.4)
addButton = Button(self.addWindow,height = 5, width = 20, text="Add Task",highlightbackground="black",font=("Helvetica",10,"bold"),command=lambda:self.saveFuntion())
addButton.place(relx=0.25, rely=0.55)
def saveFuntion(self):
nameInfo = (self.nameWiget.get(1.0, END))
dateInfo = self.dateWiget.get(1.0, END)
taskInfo = self.taskWiget.get(1.0, END)
print nameInfo
task1 = Task(nameInfo,dateInfo,taskInfo)
task1.save()
self.nameWiget.delete(1.0,END)
class Task:
def __init__(self,name,date,task):
self.__name = name
self.__date = date
self.__task = task
def save(self):
fileName = open("dataFile.txt","a")
fileName.write(self.__name)
fileName.write(self.__date)
fileName.write(self.__task)
class editTask:
def __init__(self):
self.editWindow = Tk()
self.newWindow = Tk()
self.newWindow.geometry("450x750")
self.editWindow.configure(background = "black")
self.editWindow.geometry("450x750")
self.editWindow.resizable(width = False, height = False)
self.editWindow.title("Edit Task")
self.listBox = Listbox(self.editWindow,heigh = 15, width = 30)
self.listBox.place(relx = 0.2, rely = 0.6)
#drop down menu
self.var = StringVar(self.editWindow)
self.var.set("Select search critria")
self.choices = ["Name","Date"]
self.option = OptionMenu(self.editWindow,self.var,*self.choices)
self.option.configure(bg = "black")
self.option.place(relx = 0.5, rely = 0.2)
#edit label and text box
self.editLabel = Label(self.editWindow,text="Add the name of the task",font = ("Helvetica",10,"italic"),bg = "black",fg = "white")
self.editLabel.place(relx=0.01, rely=0.05)
self.editInfoWiget = Text (self.editWindow, width = 63, height = 1)
self.editInfoWiget.place(relx=0.0, rely=0.1)
# search button
searchButton = Button(self.editWindow,height = 5, width = 20, text="Search for Task",highlightbackground="black",font=("Helvetica",10,"bold"),command=lambda:self.searchFuntion())
searchButton.place(relx=0.3, rely=0.4)
def searchFuntion(self):
critria = self.var.get()
info = self.editInfoWiget.get(1.0,END)
thing = info.split("\n")
thing2 = thing[0]
search = searchCritria(critria,thing2)
search.search()
# def openListBox(self):
class searchCritria():
def __init__(self,critria,info):
self.__critria = critria
self.__info = info
def search(self):
self.file = open("dataFile.txt", "r+")
fileData = self.file.readlines()
self.file.close()
lengthOfFile = len(fileData)
counter = 1
self.name = []
self.date = []
self.details = []
for i in range (lengthOfFile):
split = fileData[i].split("\n")
while counter == 1:
self.name.append(split)
break
while counter == 2:
self.date.append(split)
break
while counter == 3:
self.details.append(split)
break
counter = counter +1
if counter > 3:
counter = 1
if self.__critria == "Name":
for x in range (len(self.name)):
self.taskName = self.name[x]
self.taskName2 = self.taskName[0]
if self.__info == self.taskName2:
openWindow = True
else :
openWindow = False
if openWindow == True:
editTask().listBox.insert(END,self.taskName2)
if self.__critria == "Date":
for x in range (len(self.date)):
self.taskDate = self.date[x]
self.taskDate2 = self.taskDate[0]
if self.__info == self.taskDate2:
print "found"
else :
print"not found"
class editTask2():
def __init__(self):
self.edit2Window = Tk()
self.edit2Window.configure(background = "black")
self.edit2Window.geometry("450x350")
self.edit2Window.resizable(width = False, height = False)
self.edit2Window.title("Edit Task")
any help would be great
thanks
The biggest problem in your code is that you're creating multiple instances of Tk. Tkinter simply isn't designed to work that way. You should only ever create a single instance of Tk. If you need additional windows, create instances of Toplevel.
Also, you need to call the mainloop function of this instance of Tk exactly once. Without it, your GUI will not work.
If you want to update a listbox in another class than where it was created, the concept is pretty simple: if A needs to update B, A needs a reference to B. So, either pass in a reference to the listbox when you create the other class, or give the other class a method you can call where you pass in the reference to the listbox after it was created.

Categories

Resources