I am trying to create an application in Python GUI using tkinter. Here is the code I'm using for the GUI part. Whenever I try to access my Entry Widget I get error.
Ex:Sin_put.get() should give me the text in the Entry widget but it gives me an error
AttributeError: 'NoneType' object has no attribute 'get'
I'm relatively new to Python. So if you guys have any suggestions to improve the functionality you're most welcome.
from tkinter import *
from tkinter import ttk
sys.path.insert(0, 'home/ashwin/')
import portscanner
class App:
def __init__(self, master):
master.option_add('*tearOff', False)
master.resizable(False,False)
self.nb = ttk.Notebook(master)
self.nb.pack()
self.nb.config(width=720,height=480)
self.zipframe = ttk.Frame(self.nb)
self.scanframe = ttk.Frame(self.nb)
self.botframe = ttk.Frame(self.nb)
self.mb = Menu(master)
master.config(menu = self.mb)
file = Menu(self.mb)
info = Menu(self.mb)
self.mb.add_cascade(menu = file, label = 'Tools')
self.mb.add_cascade(menu = info, label = 'Help')
file.add_command(label='Zip Cracker', command = self.zipframe_create)
file.add_command(label='Port Scanner', command = self.scanframe_create)
file.add_command(label='Bot net', command =self.botframe_create)
info.add_command(label='Usage', command=(lambda:print('Usage')))
info.add_command(label='About', command=(lambda:print('About')))
def zipframe_create(self):
self.nb.add(self.zipframe,text='Zip')
self.zipframe.config(height=480,width=720)
zlabel1 = ttk.Label(self.zipframe, text='Select the zip file').grid(row=0,column=0, padx=5, pady=10)
zlabel2 = ttk.Label(self.zipframe, text='Select the dictionary file').grid(row=2,column=0, padx=5)
ztext1 = ttk.Entry(self.zipframe, width = 50).grid(row=0,column=1,padx=5,pady=10)
ztext2 = ttk.Entry(self.zipframe, width = 50).grid(row=2,column=1,padx=5)
zoutput = Text(self.zipframe, width=80, height=20).grid(row=3,column=0,columnspan = 3,padx=5,pady=10)
zb1 = ttk.Button(self.zipframe, text='Crack', width=10).grid(row=0,column=2,padx=5,pady=10)
def scanframe_create(self):
self.nb.add(self.scanframe,text='Scan')
self.scanframe.config(height=480,width=720)
slabel1 = ttk.Label(self.scanframe, text='IP address').grid(row=0,column=0, padx=5, pady=10)
sin_put = ttk.Entry(self.scanframe, width = 50).grid(row=0,column=1,padx=5,pady=10)
soutput = Text(self.scanframe, width=80, height=20).grid(row=3,column=0,columnspan = 3,padx=5,pady=10)
sb1 = ttk.Button(self.scanframe, text='Scan', width=6,command= print('Content: {}'.format(sin_put.get()))).grid(row=0,column=2,padx=5,pady=10)
def botframe_create(self):
self.nb.add(self.botframe,text='Bot')
self.botframe.config(height=480,width=720)
blabel1 = ttk.Label(self.botframe, text='IP address').grid(row=0,column=0, padx=5, pady=10)
blabel2 = ttk.Label(self.botframe, text='Username').grid(row=1,column=0, padx=2)
blabel3 = ttk.Label(self.botframe, text='password').grid(row=2,column=0, padx=2)
btext1 = ttk.Entry(self.botframe, width = 30).grid(row=0,column=1,padx=5,pady=10)
btext2 = ttk.Entry(self.botframe, width = 30).grid(row=1,column=1)
btext2 = ttk.Entry(self.botframe, width = 30).grid(row=2,column=1)
boutput = Text(self.botframe, width=80, height=20).grid(row=3,column=0,columnspan = 3,padx=5,pady=10)
bb1 = ttk.Button(self.botframe, text='Connect', width=8).grid(row=2,column=2,padx=5,pady=10)
def main():
root = Tk()
feedback = App(root)
root.mainloop()
if __name__ == "__main__": main()
grid() returns None so sin_put will always equal None. Instead of passing the Tkinter ID to grid() you have to store it first if you want to reference it later. Note that for the Buttons, putting it all on one line is fine as you don't use the button's ID later.
sin_put=ttk.Entry(self.scanframe, width = 50) ## stores the return ID from Entry
sin_put.grid(row=0,column=1,padx=5,pady=10) ## don't catch return from grid as it is None
Related
I am creating instances of two different objects (features_object and line_object) on a canvas. The idea is to connect several of the features by lines (). Later on when features are moved around the lines should follow.
At the moment my issue is that, when I apply the delete method on the lines I can delete them (Lines created between features by left mouse click. Line deleted by right mouse double click). However with the similar method of the feature class nothing happens! I cannot delete the features! The features seem invisible on the canvas! Is there any solution to that?
Thanks a lot!
from tkinter import Tk, Frame, Canvas, Text, END, TRUE, BOTH, CURRENT
click = 0
class line_object:
all_connections = []
def __init__(self):
self.connections_data = []
def create_line(self, master, start_elem, end_elem, tag_start, tag_end):
self.master = master
self.start_elem = start_elem
self.end_elem = end_elem
self.tag_start = tag_start
self.tag_end = tag_end
self.start_x = self.master.coords(self.start_elem)[0]
self.start_y = self.master.coords(self.start_elem)[1]
self.end_x = self.master.coords(self.end_elem)[0]
self.end_y = self.master.coords(self.end_elem)[1]
self.line_tag = (f'Connector_{self.start_elem}_{self.end_elem}', 'connection', 'drag')
self.master.delete(self.line_tag)
self.line_id = self.master.create_line(self.start_x, self.start_y, self.end_x, self.end_y, fill="red", width=6, tags=(self.line_tag, self.tag_start, self.tag_end))
self.master.tag_lower(self.line_id)
self.bind_events_lines()
def bind_events_lines(self):
self.master.bind('<Double Button-3>', self.deleteLine)
def deleteLine(self, event=None):
actual = self.master.find_withtag(CURRENT)
self.master.delete(actual)
class features_object():
def __init__(self):
self.features_data = []
def create_feature(self, master, feature_text, feature_xpos, feature_ypos, feature_color):
self.master = master
self.feature_text = feature_text
self.feature_xpos = feature_xpos
self.feature_ypos = feature_ypos
self.feature_color = feature_color
self.feature_frame = Frame(self.master, bg=self.feature_color, border=20)
self.feature_text = Text(self.feature_frame, font=("Helvetica", 12), relief='flat', width=20, height=3, selectbackground=self.feature_color, selectforeground="black", exportselection=TRUE)
self.feature_text.grid(row=0, column=0, padx=5, pady=5, sticky='w')
self.feature_text.config(wrap='word')
self.feature_text.insert(END, feature_text)
self.feature_tags = 'drag'
self.feature_id = self.master.create_window(self.feature_xpos, self.feature_ypos, window=self.feature_frame, tags=self.feature_tags)
self.master.itemconfigure(self.feature_id, tags=[self.feature_id])
self.bind_events_features()
def bind_events_features(self):
self.feature_frame.bind('<Button-1>', self.draw_line_with_bind)
self.feature_frame.bind('<Double Button-3>', self.deleteFeature)
def deleteFeature(self, event):
actual = self.master.find_withtag(CURRENT)
self.master.delete(actual)
def draw_line_with_bind(self, event):
global click, start_x, start_y, end_x, end_y, elem_start, tag_start
if click == 0:
elem_start = self.feature_id
tag_start = f'{elem_start}'
click = 1
elif click == 1:
elem_end = self.feature_id
tag_end = f'{elem_end}'
lin = line_object()
self.connection = lin.create_line(draw_canvas, elem_start, elem_end, tag_start, tag_end)
click = 0
window = Tk()
window.geometry("1000x800")
frame_start = Frame(window)
frame_start.pack(expand=TRUE, fill=BOTH)
draw_canvas = Canvas(frame_start)
draw_canvas.pack(expand=TRUE, fill=BOTH)
features_object().create_feature(draw_canvas, 'feature A', 100, 100, 'red')
features_object().create_feature(draw_canvas, 'feature B', 300, 300, 'green')
features_object().create_feature(draw_canvas, 'feature C', 500, 500, 'magenta')
def read_id(event):
currently_clicked = draw_canvas.find_withtag(CURRENT)
print(f'Currently clicked instance {currently_clicked}')
draw_canvas.bind('<Button-2>', read_id)
if __name__ == '__main__':
window.mainloop()
I'm having some problems making my gif work in this code.
its a kind of media player with a graphic equalizer :)
I'm trying to make gif play inside the "pantalla" label. I'm having an attribute error with the frame variable. I've been looking around but cannot solve the problem.
sorry for my mistakes I'm a newbie.
any help will be appreciated.
here the code:
import os
from tkinter import *
from vlc import Instance
import time
app = Tk()
app.title("JlMultimedia")
app.iconbitmap("C:/Users/Thunder/Documents/Projects/Python/auricular.ico")
app.geometry("340x250")
app.config(bg="blue")
frames = [PhotoImage(file='C:/Users/Thunder/Documents/Projects/Python/imagenes/equalizer1.gif', format = 'gif -index %i' %(i)) for i in range(5)]
def update(self, ind):
self.frame = frames[ind]
ind += 1
print(ind)
if ind>4: #With this condition it will play gif infinitely
ind = 0
app.after(100, update, ind)
class Jlmultimedia:
def __init__(self):
self.Player = Instance('--loop')
capa = Frame(app)
capa.config(bg="#ffffff")
capa.pack(expand="1")
capa1 = Frame(capa, bg="#0000ff")
capa1.config()
capa1.pack(expand="1")
pantalla = Label(capa1, image=self.frame)
pantalla.grid(row="0", columnspan="3")
self.playimage = PhotoImage(file="C:/Users/Thunder/Documents/Projects/Python/imagenes/play4.png")
self.stopimage = PhotoImage(file="C:/Users/Thunder/Documents/Projects/Python/imagenes/stop4.png")
self.pauseimage = PhotoImage(file="C:/Users/Thunder/Documents/Projects/Python/imagenes/pause4.png")
self.nextimage = PhotoImage(file="C:/Users/Thunder/Documents/Projects/Python/imagenes/forw4.png")
self.backimage = PhotoImage(file="C:/Users/Thunder/Documents/Projects/Python/imagenes/rew4.png")
capa2 = LabelFrame(capa)
capa2.config(bg="#ffffff")
capa2.pack(expand="1")
playboton = Button(capa2, image=self.playimage, bd="0", command=self.play)
playboton.grid(row="1", column="1")
self.volVar = IntVar()
volboton = Scale(capa2, from_=100, to=0, resolution=1, length=90,
label="Vol", variable=self.volVar, command=self.set_volume)
volboton.grid(row="1", column="6")
stopboton = Button(capa2, image=self.stopimage, bd="0", command=self.stop)
stopboton.grid(row="1", column="2")
pauseboton = Button(capa2, image=self.pauseimage, bd="0", command=self.pause)
pauseboton.grid(row="1", column="4")
nextboton = Button(capa2, image=self.nextimage, bd="0", command=self.next)
nextboton.grid(row="1", column="3")
preboton = Button(capa2, image=self.backimage, bd="0", command=self.previous)
preboton.grid(row="1", column="5")
# panel to hold player time slider
self.timeVar = DoubleVar()
self.timeSliderLast = 0
self.timeSlider = Scale(capa1, variable=self.timeVar, command=self.OnTime,
from_=0, to=1000, orient=HORIZONTAL, length=328, showvalue=0) # label='Time',
#self.timeSlider.pack(side=BOTTOM, fill=X, expand=1)
self.timeSliderUpdate = time.time()
self.timeSlider.grid(row="1", columnspan="5")
def addPlaylist(self):
self.mediaList = self.Player.media_list_new()
path = r"C:/Users/Thunder/Documents/Projects/Python/musica"
songs = os.listdir(path)
for s in songs:
self.mediaList.add_media(self.Player.media_new(os.path.join(path,s)))
self.listPlayer = self.Player.media_list_player_new()
self.listPlayer.set_media_list(self.mediaList)
def set_volume(self, *unuse):
vol = min(self.volVar.get(), 100)
self.listPlayer.get_media_player().audio_set_volume(vol)
def play(self):
self.listPlayer.play()
def next(self):
self.listPlayer.next()
def pause(self):
self.listPlayer.pause()
def previous(self):
self.listPlayer.previous()
def stop(self):
self.listPlayer.stop()
def OnTime(self, *unused):
if self.listPlayer:
t = self.timeVar.get()
if self.timeSliderLast != int(t):
self.listPlayer.get_media_player().set_time(int(t * 1e3)) # milliseconds
self.timeSliderUpdate = time.time()
myPlayer = Jlmultimedia()
myPlayer.addPlaylist()
app = mainloop()
There are several issues:
update() has never been executed
image option of label pantalla should be update as well inside update()
pantalla is a local variable inside Jlmultimedia.__init__(), you should make it instance variable self.pantalla
self.frame is undefined
app = mainloop() should be app.mainloop()
Below is a modified update():
def update(ind=0):
myPlayer.pantalla.config(image=frames[ind%len(frames)])
app.after(100, update, ind+1)
And changing pantalla to instance variable inside __init__():
class Jlmultimedia:
def __init__(self):
...
self.pantalla = Label(capa1)
self.pantalla(row=0, columnspan=3)
...
Then call update() before app.mainloop():
...
update()
app.mainloop()
I am using Pycharm and Python 3.8.
My Tkinter window stops responding and causes my program to crash.
Pycharm presents the following line in its output: Process finished with exit code -805306369 (0xCFFFFFFF)
I have the following code for displaying the progress of a for loop:
import tkinter as tk
from tkinter import filedialog, ttk
from tkinter.ttk import Progressbar
import json
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.filename = ''
tk.Button(self, text = 'Upload File', command = self.get_file).grid(row = 0, column = 0)
tk.Button(self, text = 'Verify', command = self.verify).grid(row = 1, column = 0)
# tk.Label(self, text = 'some name').grid(row = 0, column = 1)
self.mainloop()
def get_file(self):
self.filename = tk.filedialog.askopenfilename(title = "Select File", filetypes = [("JSON", "*.json")])
tk.Label(self, text = self.filename).grid(row = 0, column = 1)
def verify():
lbl = tk.Label(self, text = 'Verifying Trustee Public Keys')
lbl.grid(row = 2, column = 0)
prog1 = ttk.Progressbar(self,
length = 100,
orient = "horizontal",
maximum = len(self.data["trustee_public_keys"]),
value = 0)
prog1.grid(row = 3, column = 0)
i = 1
for trustee_key_list in self.data['trustee_public_keys']:
print('Trustee :', i)
//some code
i = i+1
prog1['value'] = i
The get_file part works. But, when I click the verify button to execute the verify() function. The entire window freezes and I get a not responding message.
WHat is the problem with the following part of my code?
lbl = tk.Label(self, text = 'Verifying Trustee Public Keys')
lbl.grid(row = 2, column = 0)
What am I doing wrong?
I have tried in several ways, set it with ttk.Progressbar, with self.progresso.Progressbar ... and nothing, anyone can help? I'm still young then sorry for ignorance. If they can be as clear as possible, thank you.
from tkinter import *
from tkinter import ttk
import time
class users_Arduino:
def __init__(self,window):
self.wind = window
self.wind.title("System F2T - Cadastro Arduino")
menubar = Menu(window)
arduino = Menu(menubar,tearoff=0)
menubar.add_cascade(label = "Arduino",menu=arduino)
arduino.add_command(label = "Conectar/Inserir dados-BD", command=self.getSerialData)
window.config(menu = menubar)
def bar():
progress['value'] = 20
root.update_idletasks()
time.sleep(1)
progress['value'] = 40
root.update_idletasks()
time.sleep(1)
progress['value'] = 50
root.update_idletasks()
time.sleep(1)
progress['value'] = 60
root.update_idletasks()
time.sleep(1)
progress['value'] = 80
root.update_idletasks()
time.sleep(1)
progress['value'] = 100
def getSerialData(self):
self.progresso = Toplevel()
self.progresso.title("System F2T - Progress")
self.progresso.geometry("290x200")
#self.progresso["bg"] = "#000"
progress = self.Progressbar(self.progresso,orient = HORIZONTAL, length = 100, mode = 'determinate').pack(pady = 10)
Button(self.progresso, text = 'Start', command = self.bar).pack(pady = 10)
if __name__ == '__main__':
window = Tk()
window['bg'] = "#000"
users_Arduino(window)
window.mainloop()
You are trying to access a class attribute by using self.Progressbar, which obviously won't work. What you intended is to create a Progressbar, which should be done like below:
progress = ttk.Progressbar(self.progresso,orient = HORIZONTAL, length = 100, mode = 'determinate').pack(pady = 10)
Next, you wanted the Progressbar to update every second until it reaches 100, but calling time.sleep will block your main thread and freeze your GUI. You need to use root.after method.
Also if you call something=widget(...).pack() at the same line, you are not keeping a proper reference of the object. The return value will just be None.
So everything wrapped up:
from tkinter import *
from tkinter import ttk
class UsersArduino:
def __init__(self,window):
self.wind = window
self.wind.title("System F2T - Cadastro Arduino")
self.value = 0
menubar = Menu(window)
arduino = Menu(menubar,tearoff=0)
menubar.add_cascade(label = "Arduino",menu=arduino)
arduino.add_command(label = "Conectar/Inserir dados-BD", command=self.getSerialData)
window.config(menu = menubar)
def bar(self):
self.progress['value'] +=20
if self.progress['value'] <=100:
self.wind.after(1000,self.bar)
def getSerialData(self):
self.progresso = Toplevel()
self.progresso.title("System F2T - Progress")
self.progresso.geometry("290x200")
self.progress = ttk.Progressbar(self.progresso,orient = HORIZONTAL, length = 100, mode = 'determinate')
self.progress.pack(pady = 10)
Button(self.progresso, text = 'Start', command = self.bar).pack(pady = 10)
if __name__ == '__main__':
window = Tk()
window['bg'] = "#000"
UsersArduino(window)
window.mainloop()
I have this section of code that is not working properly. Was wondering whether anyone could understand what is wrong with it?
import os
from tkinter import *
import time
import sys
root = Tk()
root.attributes("-fullscreen", True)
class User_Questions:
def __init__(self, master):
self.master = master
master.title("MIT")
global frame
frame = Frame(master)
frame.pack()
self.choosen_questions = []
self.choosen_answers = []
self.choosen_questions_file = open(os.path.expanduser("~/Desktop/Bradfield/Project/" + str(test_choice) + "/Questions.txt"))
self.choosen_answers_file = open(os.path.expanduser("~/Desktop/Bradfield/Project/" + str(test_choice) + "/Answers.txt"))
for line in self.choosen_questions_file:
self.new_question = line.replace("\n","")
self.choosen_questions.append(self.new_question)
for line in self.choosen_answers_file:
self.new_answer = line.replace("\n","")
self.choosen_answers.append(self.new_answer)
self.correct_answers = 0
self.question_label = Label(frame, text = self.choosen_questions[0].replace("1. ",""), font = "Helvetica", fg = "blue")
self.question_label.pack()
self.answer_entry = Entry(frame, text = "", font = "Helvetica")
self.answer_entry.pack()
self.answer_entry.bind('<Return>', self.question)
self.check_test_exists_button = Button(frame, text="SUBMIT", font = "Helvetica", command=self.question)
self.check_test_exists_button.pack()
self.back_button = Button(frame, text="GO BACK", font = "Helvetica", command=self.go_back)
self.back_button.pack()
self.quit_button = Button(frame, text="QUIT", font = "Helvetica", command=master.destroy)
self.quit_button.pack()
def question(self, event):
for i in range(1, len(self.choosen_questions)):
return(self.choosen_questions[i+1].replace(i+". ",""))
def go_back(self):
frame.destroy()
my_gui = User_Choose_Test(root)
This is the error that outputs:
AttributeError: 'User_Questions' object has no attribute 'question'
The indentation of question and go_back is incorrect. It needs to be un-indented one level.